下列example http://www.scala-lang.org/node/114 from 斯卡拉之旅显示如何使用隐式根据类型提供适当的缺失成员(add 和 unit)。编译器将在范围内选择正确的隐式对象。该库还使用它List.sortBy
and Ordering
or List.sum
and Numeric
例如。
然而,B 类中的以下用法是隐式参数的有效/推荐用法(而不是在 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)
当沿着堆栈传递参数时,我主要使用隐式来节省调用站点的一些输入。
这是一个非常好的用例。实际上,当范围决定要使用的参数时,我建议这样做。它提供了一种优雅的方式将某种上下文传递到插件类中,以便实用程序函数可以使用该上下文。例如:
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)
你可以看到一个例子我正在玩的数据库迁移系统 http://suereth.blogspot.com/2008/11/using-partial-functions-and-pattern.html。查看 Migration 类及其 MigrationContext。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)