Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala implicit conversion issue

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.

like image 554
elk Avatar asked Feb 06 '12 12:02

elk


1 Answers

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.

like image 172
Dylan Avatar answered Oct 10 '22 13:10

Dylan