Scala 隐式转换不起作用

scala implicit conversion doesn't work

我发现一个奇怪的现象:

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!

根据隐式搜索规则,应该应用object T中的方法doubleDual。但事实并非如此。我必须手动导入 a.T._。为什么?

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

在我看来 搜索应该找到 两个 隐式:a.T.doubleDuala.dual.dual.T.doubleDual 问题是为什么它没有' t 给出 "implicit conversions are not applicable because they are ambiguous" 错误。也许是因为他们同名?

不,那是错误的,a.dual.dual.T.doubleDual类型错误。但我仍然怀疑问题可能与搜索a.Ta.dual.dual.T时出现两次T对象有关。只是这将是一个编译器错误,除非我错过了其他东西。

关键是"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

但重命名后:

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