Scala implicit conversion problem

I have an implicit conversion problem in the following code:

trait A { def send(s: String): String = { println(s) s } } object X { implicit def toB(a: A): B = new B(a) class B(a: A) { def <<(s: String): String = a send s } } object Y { implicit def toB(a: A): B = new B(a) class B(a: A) { } } object Test extends App { import X._ import Y._ val a: A = new A {} a << "Test" } 

The last statement in Test causes a compilation error:

 error: value << is not a member of A a << "Test" 

However, if I import Y._ from Test, it compiles fine.

Note that in real code, both XB and YB are part of the Scala DSL for the Java library, and I would like to be able to use them in the same compilation unit.

+6
source share
1 answer

It seems that Y.toB overrides X.toB when importing into one area. If I put import Y._ before this import X._ , then it will work. Also, if I rename Y implicitly to something else (like toYB ), then it works regardless of the order in which you insert it.

+7
source

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


All Articles