【发布时间】:2011-07-13 22:47:48
【问题描述】:
给定一个游戏的类型层次结构,它强烈区分下一个轮到谁:
trait Game
trait BlackToPlay extends Game {
def move(p: BlackPiece, s: Square): Either[FinishedGame, WhiteToPlay]
}
trait WhiteToPlay extends Game {
def move(p: WhitePiece, s: Square): Either[FinishedGame, BlackToPlay]
}
我可以在不借助反思的情况下做出以下重要的断言吗?
"A game with white to play" should {
"not allow black to play" in {
// an instance of whiteToPlay should not
// have the `move(BlackPiece, Square)` method.
}
}
编辑:我尝试实施@Martin 的解决方案不起作用。对这里有什么问题有任何想法吗?来自 REPL:
scala> class B() {
| def b(s: String) = s
| }
defined class B
scala> val b = new B()
b: B = B@420e44
scala> b.c("")
<console>:8: error: value c is not a member of B
b.c("")
^
scala> b match {
| case _: { def c(s: String) } => false
| case _ => true
| }
warning: there were unchecked warnings; re-run with -unchecked for details
res7: Boolean = false
res7 应该是 true,因为 b 不应该匹配 { def c(s: String) } 的结构类型
【问题讨论】:
-
阅读警告,然后使用
-unchecked重新运行。您将看到一个警告,大意是结构类型擦除到AnyRef。或者,换句话说,它总是被接受。 -
或者甚至输入
:power然后settings.unchecked.value = true来激活-unchecked。