蘇哲聖
蘇哲聖

Reputation: 795

scala implicit conversion doesn't work

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?

Upvotes: 1

Views: 172

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170839

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.

Upvotes: 1

蘇哲聖
蘇哲聖

Reputation: 795

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

Upvotes: 0

Related Questions