scalaimplicit-conversionimplicitimplicits

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?


Solution

  • 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