mis*_*tor 6 scala implicit-conversion
scala> implicit def transitive[A, B, C](implicit f: A => B, g: B => C): A => C = f andThen g
transitive: [A, B, C](implicit f: A => B, implicit g: B => C)A => C
scala> class Foo; class Bar; class Baz { def lol = println("lol") }
defined class Foo
defined class Bar
defined class Baz
scala> implicit def foo2Bar(f: Foo) = new Bar
foo2Bar: (f: Foo)Bar
scala> implicit def bar2Baz(f: Bar) = new Baz
bar2Baz: (f: Bar)Baz
scala> implicitly[Foo => Baz]
<console>:14: error: diverging implicit expansion for type Foo => Baz
starting with method transitive in object $iw
implicitly[Foo => Baz]
Run Code Online (Sandbox Code Playgroud)
从上面的代码中可以明显看出,我正在尝试编写一个方法,该方法在范围内导入时会使隐式转换具有传递性.我期待这段代码可以工作,但令人惊讶的是它没有.上述错误消息的含义是什么,以及如何使此代码有效?
更新:正如评论中所指出的,这种方法不能在 2.8 上编译,虽然可以implicitly[Foo => Baz]正常工作,(new Foo).lol但不能。
transitive如果您将其重命名为conforms以隐藏该方法,则效果很好Predef:
implicit def conforms[A, B, C](implicit f: A => B, g: B => C): A => C = f andThen g
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅此答案。
附带说明:-Xlog-implicits在这种情况下启动 REPL 是一种获取更多信息性错误消息的便捷方法。在这种情况下,一开始并没有多大帮助:
scala> implicitly[Foo => Baz]
scala.this.Predef.conforms is not a valid implicit value for Foo => Baz because:
type mismatch;
found : <:<[Foo,Foo]
required: Foo => Baz
<console>:14: error: diverging implicit expansion for type Foo => Baz
starting with method transitive in object $iw
implicitly[Foo => Baz]
^
scala.this.Predef.conforms is not a valid implicit value for Foo => Baz because:
type mismatch;
found : <:<[Foo,Foo]
required: Foo => Baz
transitive is not a valid implicit value for Unit => Foo => Baz because:
not enough arguments for method transitive: (implicit f: A => B, implicit g: B => C)A => C.
Unspecified value parameter g.
transitive is not a valid implicit value for => Unit => Foo => Baz because:
not enough arguments for method transitive: (implicit f: A => B, implicit g: B => C)A => C.
Unspecified value parameter g.
Run Code Online (Sandbox Code Playgroud)
但是,如果我们暂时重写foo2Bar和bar2Baz为函数,我们会收到一条错误消息,突出显示了其中的歧义:
implicit val foo2Bar = (_: Foo) => new Bar
implicit val bar2Baz = (_: Bar) => new Baz
scala> implicitly[Foo => Baz]
transitive is not a valid implicit value for Foo => Baz because:
ambiguous implicit values:
both method conforms in object Predef of type [A]=> <:<[A,A]
and value foo2Bar in object $iw of type => Foo => Bar
match expected type Foo => B
Run Code Online (Sandbox Code Playgroud)
现在很明显我们只需要影子conforms。