Curious error message

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 follows from the above code, I'm trying to write a method that, when imported into a region, will make implicit conversions transitive. I expected this code to work, but surprisingly it is not. What does the above error message mean, and how can I get this code to work?

+6
source share
1 answer

Update: As noted in the comments, this approach does not compile on 2.8, but for now implicitly[Foo => Baz] works correctly, (new Foo).lol does not work.


This works great if you rename your transitive to conforms to obscure 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: running REPL with -Xlog-implicits is a convenient way to get more informative error messages in such situations. In this case, first do not help much:

 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 as functions, we get an error message that emphasizes 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 obscure the conforms .

+4
source

Source: https://habr.com/ru/post/900348/


All Articles