在Scala中隐含对象

cfc*_*hou 6 scala object implicit

我对Joshua Suareth的书Scala中的"5.1.3隐式解决方案"中的描述感到困惑,第100页:

Scala对象不能包含implicits的伴随对象.因此,必须从外部作用域提供与该对象类型的隐式作用域所需的对象类型相关的隐含.这是一个例子:

scala> object Foo {
     |   object Bar { override def toString = "Bar" }
     |   implicit def b : Bar.type = Bar 
     |}
defined module Foo
scala> implicitly[Foo.Bar.type]
res1: Foo.Bar.type = Bar
Run Code Online (Sandbox Code Playgroud)

但是我在REPL中隐藏了对象Bar:

scala> object Foo {
     |   implicit object Bar {
     |     override def toString = "isBar" }
     | }
defined module Foo
scala> implicitly[Foo.Bar.type]
res0: Foo.Bar.type = isBar
Run Code Online (Sandbox Code Playgroud)

似乎它不需要在外部范围中定义隐式.或者我认为约书亚的意思完全错了?

Mil*_*bin 8

在这种情况下,对象就好像它们是自己的伙伴一样,所以你只需要在对象本身的体内嵌套对象类型提示的含义,

scala> object Bar {
     |   override def toString = "Bar"
     |   implicit def b : Bar.type = Bar
     | }
defined module Bar

scala> implicitly[Bar.type]
res0: Bar.type = Bar
Run Code Online (Sandbox Code Playgroud)

请注意,此处的主体Bar已被视为隐式解析范围的一部分Bar.type.

这可能看起来是Scala类型系统的一个模糊的角落,但我能够很好地利用无形状多态(函数)值编码.