1

我只是在 scala 中检查结构类型的相等性。

我立即从匿名类创建一个foo实例和一个Q类型。我打算将它们与方法名称不同,以便希望它们在结构上被视为不同的类型。

代码片段:

scala> val foo = new {def foo=1}
a: AnyRef{def foo: Int} = $anon$1@3885c37f

scala> type Q = {def q:Unit}
defined type alias Q

scala> foo.isInstanceOf[Q]
<console>:14: warning: a pattern match on a refinement type is unchecked
              foo.isInstanceOf[Q]
                            ^
res55: Boolean = true

检查返回真。

Q1: 我不明白为什么fooQ. 那是胡说八道。它们在类型结构的意义上不是不同的吗?

Q2: 那么检查结构类型的正式方法是什么?

4

1 回答 1

1

isInstanceOf是根据班级信息。在您的情况下,您需要输入信息:

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

scala> val foo = new {def foo=1}
foo: AnyRef{def foo: Int} = $anon$1@15ab47

scala> type Q = {def q:Unit}
defined type alias Q

scala> def getType[T : TypeTag](t: T) = implicitly[TypeTag[T]].tpe
getType: [T](t: T)(implicit evidence$1:reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.Type

scala> getType(foo) =:= typeOf[Q]
res9: Boolean = false
于 2014-06-10T06:34:31.053 回答