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]
As should be obvious from the above code, I am trying to write a method which when imported in scope will make implicit conversions transitive. I was expecting this code to work, but surprisingly it doesn't. What does the above error message mean, and how can I make this code work?
Update: As noted in the comments, this approach doesn't compile on 2.8, and while implicitly[Foo => Baz]
works correctly, (new Foo).lol
doesn't.
This works just fine if you rename your transitive
to conforms
to shadow the method in Predef
:
implicit def conforms[A, B, C](implicit f: A => B, g: B => C): A => C = f andThen g
See this answer for more details.
As a side note: starting the REPL with -Xlog-implicits
is a handy way to get more informative error messages in situations like this. In this case it's not a lot of help at first:
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.
But if we temporarily rewrite foo2Bar
and bar2Baz
to be functions, we get an error message that highlights the ambiguity:
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
Now it's clear that we just need to shadow conforms
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With