比较Scala中的类型

时间:2012-10-03 01:16:00

标签: scala

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

trait Bar {
  type MyType
}

object Bar {
  def compareTypes(left: Bar, right: Bar): Boolean = (left.MyType == right.MyType)
}

但是,编译失败,“值MyType不是Bar的成员”。

发生了什么事?有没有办法做到这一点?

1 个答案:

答案 0 :(得分:9)

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

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
}

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

val intBar1 = new Bar { type MyType = Int }
val intBar2 = new Bar { type MyType = Int }
val strBar1 = new Bar { type MyType = String }

按预期工作:

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

scala> Bar.compareTypes(intBar1, intBar2)
res1: Boolean = true

诀窍是要求L#MyTypeR#MyType相同的隐含证据,并提供默认值(null),如果不相同的话。然后你可以检查一下你是否得到了默认值。

相关问题