That's because the Scala compiler has no way how to figure out that you want to convert a B
to an A
just by looking at this piece of code:
val b = new B
b.hello // I know the source type is B, but what's the target type?
Consider the case where there's a C
similar to your A
. Which of the two conversions should Scala choose? It's too much to ask Scala to search all the other companion objects in the system for a possible implicit conversion from the, already known, source type. And it's quite possible that it'll end up with an ambiguous result.
The easiest solution in your case is to move the B
to A
conversion from the companion object of A
to the companion object of B
.
class A {
def hello=println("hello")
}
class B
object B {
implicit def b2a(b:B)=new A
}
object ImplicitConversion extends App {
val b=new B
b.hello
}