6

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

trait Bar {
  type MyType
}

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

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

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

4

1 回答 1

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
}

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

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如果不是,则提供默认值 ( )。然后你可以检查你是否得到默认值。

于 2012-10-03T01:42:00.153 回答