【问题标题】:Type equality in the Scala 2.10 Reflection APIScala 2.10 反射 API 中的类型相等
【发布时间】:2012-06-30 13:52:42
【问题描述】:

我在Scala 2.10.0 Milestone 4 中遇到了一个奇怪的问题,我无法解决这个问题。首先是按我期望的方式工作的东西:

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> trait A[X]; trait B[Y] extends A[Y]
defined trait A
defined trait B

scala> typeOf[B[String]].parents
res0: List[reflect.runtime.universe.Type] = List(java.lang.Object, A[String])

scala> typeOf[B[String]].parents contains typeOf[A[String]]
res1: Boolean = true

类似地(在同一会话中):

scala> trait D; trait E extends A[D]
defined trait D
defined trait E

scala> typeOf[E].parents
res2: List[reflect.runtime.universe.Type] = List(java.lang.Object, A[D])

scala> typeOf[E].parents contains typeOf[A[D]]
res3: Boolean = true

这并不奇怪:我可以询问类型的父母并得到我所期望的。现在我基本上结合了上面的两个例子:

scala> trait F extends A[String]
defined trait F

scala> typeOf[F].parents
res4: List[reflect.runtime.universe.Type] = List(java.lang.Object, A[String])

scala> typeOf[F].parents contains typeOf[A[String]]
res5: Boolean = false

我不明白这怎么可能是假的。如果我有 F 扩展 A[Seq[D]]A[Int] 等,也会发生同样的事情。我缺少什么可以使这种行为有意义的概括?

【问题讨论】:

  • 我刚刚确认这已在 2.10.0-M5 中修复。

标签: scala reflection types scala-2.10


【解决方案1】:

另一个奇怪的例子:

scala> val atype = typeOf[A[String]]
atype: reflect.runtime.universe.Type = A[String]

scala> val atype2 = typeOf[F].parents(1)
atype2: reflect.runtime.universe.Type = A[String]

scala> typeOf[F].parents contains atype
res39: Boolean = false

scala> typeOf[F].parents contains atype2
res40: Boolean = true

我认为您看到了一个与此类似的错误:https://issues.scala-lang.org/browse/SI-5959(尽管我已经确认这种奇怪现象也发生在 REPL 之外)。

【讨论】:

【解决方案2】:

这是一个错误。今天早上我打算调查并修复它。

编辑。这似乎是泄漏到用户空间的 Scala 反射 API 的实现细节。它不容易修复,所以现在我们保持原样,但会研究改进的可能性。

同时,为了得到正确的结果,应该始终使用=:=来比较类型,而不是==

【讨论】:

    猜你喜欢
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多