我在 Scala 中编写俄罗斯方块作为练习,我遇到了这种奇怪的行为:
abstract class Orientation(protected val index: Int) {
private[Orientation] val impls: Array[Orientation] = Array(OrientedLeft, OrientedUp, OrientedRight, OrientedDown)
def rotateCounterClockwise = impls(
if (index == 0) 3
else index - 1
)
def rotateClockwise = impls((index + 1) % 4)
}
object OrientedLeft extends Orientation(0) {
override def toString = "Left"
}
object OrientedUp extends Orientation(1) {
override def toString = "Up"
}
object OrientedRight extends Orientation(2) {
override def toString = "Right"
}
object OrientedDown extends Orientation(3) {
override def toString = "Down"
}
object Test extends Application {
var orientation: Orientation = OrientedUp
for (i <- 0 until 20) {
println("Oriented to: "+ orientation)
orientation = orientation.rotateClockwise
}
}
运行测试给出以下输出:
Oriented to: Up
Oriented to: Right
Oriented to: Down
Oriented to: null
后面跟着一个 java.lang.NullPointerException 显然。我的意思是:这到底是怎么回事?