scala implicit conversion doesn't work

167 Views Asked by At

I discover a strange phenomenon:

class A {
  val dual: A = this
  object T {
    implicit def doubleDual(t: T): dual.dual.T = t.asInstanceOf[dual.dual.T]
    implicit def justForTest(t: T): Int = 777
  }
  class T
}
val a = new A
val t = new a.T
// import a.T._
val x: Int = t //this works!
val t1: a.dual.dual.T = t //this doesn't work!

According to implicit search rule, the method doubleDual in object T should be applied. But it doesn't. I have to import a.T._ manually. Why?

2

There are 2 best solutions below

2
蘇哲聖 On BEST ANSWER

The key is "the same name"!

class A {
  val dual: A = this
  object T {
    implicit def doubleDual(t: T): dual.dual.T = t.asInstanceOf[dual.dual.T]
  }
  class T
}
val a = new A
val t = new a.T
import a.T.doubleDual  //
import a.dual.dual.T.doubleDual  //the same name!
val t1: a.dual.dual.T = t // won't compile

But after rename:

import a.T.doubleDual  //
import a.dual.dual.T.{doubleDual => dd}  // different name!
val t1: a.dual.dual.T = t // can compile
0
Alexey Romanov On

According to implicit search rule, the method doubleDual in object T should be applied.

It looks to me like the search should find two implicits: a.T.doubleDual and a.dual.dual.T.doubleDual The question is why it doesn't give "implicit conversions are not applicable because they are ambiguous" error. Maybe because they have the same name?

No, that's wrong, a.dual.dual.T.doubleDual has a wrong type. But I still suspect the problem may be related to the T object appearing twice when searching for a.T and a.dual.dual.T. It's just that this would be a compiler bug, unless I missed something else.