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]
从上面的代码中可以明显看出,我正在尝试编写一个方法,该方法在范围内导入时会使隐式转换具有传递性。我期待这段代码可以工作,但令人惊讶的是它没有。上述错误消息的含义是什么,以及如何使此代码生效?
答案 0 :(得分:4)
更新:正如评论中所述,此方法无法在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
有关详细信息,请参阅this answer。
作为旁注:使用-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.
但如果我们暂时将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
现在很清楚,我们只需要隐藏conforms
。