比较Scala中的类型

emc*_*sen 6 scala

我有两个对象,每个对象都有本地定义的类型,我想确定类型是否相同.例如,我想要编译这段代码:

trait Bar {
  type MyType
}

object Bar {
  def compareTypes(left: Bar, right: Bar): Boolean = (left.MyType == right.MyType)
}
Run Code Online (Sandbox Code Playgroud)

但是,编译失败,"值MyType不是Bar的成员".

这是怎么回事?有没有办法做到这一点?

Tra*_*own 10

你可以做到这一点,但它需要一些额外的机制:

trait Bar {
  type MyType
}

object Bar {
  def compareTypes[L <: Bar, R <: Bar](left: L, right: R)(
    implicit ev: L#MyType =:= R#MyType = null
  ) = ev != null
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我们有以下内容:

val intBar1 = new Bar { type MyType = Int }
val intBar2 = new Bar { type MyType = Int }
val strBar1 = new Bar { type MyType = String }
Run Code Online (Sandbox Code Playgroud)

它按预期工作:

scala> Bar.compareTypes(intBar1, strBar1)
res0: Boolean = false

scala> Bar.compareTypes(intBar1, intBar2)
res1: Boolean = true
Run Code Online (Sandbox Code Playgroud)

诀窍是要求隐含证据L#MyType并且R#MyType相同,并提供默认值(null)(如果不是).然后,您可以检查是否获得默认值.