I'm having a problem with implicit conversion 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 compile error:
error: value << is not a member of A
a << "Test"
However if I remove import Y._
from Test, it compiles fine.
Note that in the real code both X.B and Y.B are part of Scala DSL for a Java library and I'd like to be able to use both in the same compilation unit.
It looks like what's happening is that Y.toB
is overriding X.toB
when you import both in the same scope. If I put the import Y._
before then import X._
, then it works. Also, if I rename Y
's implicit to something else (e.g. toYB
), then it works no matter what order you put it in.
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