I'm just checking structural type equality in scala.
I create a foo
instance from annonymous class immediately and a Q
type .
I intend them to differing with method name, so that hoping them regarded as a different type structurally.
code snippet:
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
The checking returns true.
Q1:
I don't understand WHY foo
is an instance of Q
.
That's nonsense. Are not they different in sense of type structure?
Q2: So what is the formal way to checking the structural type?
isInstanceOf
is according to class info. In your case, you need type info:
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