隐式参数的有效用法 [英] Valid usages of implicit parameters

查看:99
本文介绍了隐式参数的有效用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自斯卡拉之旅的以下示例显示如何根据类型使用隐式提供适当的缺失成员(添加和单元).编译器将在范围内选择正确的隐式对象.该库还将它与List.sortByOrderingList.sumNumeric一起使用.

The following example from A Tour of Scala shows how implicit can be used to provide the appropriate missing members (add and unit) based on the type. The compiler will pick the right implicit object in scope. The library also uses that with List.sortBy and Ordering or List.sum and Numeric for instance.

但是,在类B中的以下用法是隐式参数的有效/推荐用法(与在类A中不使用隐式相反):

However is the following usage in class B a valid/recommended usage of implicit parameters (as opposed to not using implicit in class A):

class I

class A {
  def foo(i:I) { bar(i) }
  def bar(i:I) { baz(i) }
  def baz(i:I) { println("A baz " + i) }
}
(new A).foo(new I)

class B {
  def foo(implicit i:I) { bar }
  def bar(implicit i:I) { baz }
  def baz(implicit i:I) { println("B baz " + i) }
}
(new B).foo(new I)

我主要在哪里使用隐式函数,以便在沿着堆栈传递参数时节省自己在调用站点的键入内容.

Where I primarily use the implicit to save myself some typing at the call site when passing a parameter along the stack.

推荐答案

这是一个很好的用例.当范围确定要使用的参数时,我实际上建议这样做.它提供了一种优雅的方式来将某种上下文传递到Plugin类中,以便实用程序功能可以使用该上下文.例如:

This is very much a fine use case. I actually recommend this when scope determines the parameter to use. It provides an elegant way to pass some sort of context into a Plugin class so that utility functions will use the context. For example:

trait Context

object UtilityLib {
  def performHandyFunction(implicit x : Context) : SomeResult = ...
}

trait Plugin {
   def doYourThing(implicit ctx : Context) : Unit
}

class MyPlugin extends Plugin {
  def doYourThing(implicit ctx : Context) : Unit = {
    UtilityLib.performHandyFunction
  }
}

SomePluginAPI.register(new MyPlugin)

您可以在数据库迁移系统中查看示例我在玩.查看Migration类及其MigrationContext.

You can see an example in a database migration system I was toying. Check out the Migration class and its MigrationContext.

这篇关于隐式参数的有效用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆