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
.