我有一段代码依赖于某个case类的任意元素的存在,以便在该类的字段上进行操作。这里有some options,尽管几乎每个Scala博客都建议不要使用null
,但在类型级编程中似乎并不可怕(例如,以下答案:{ {3}})。但是,这段直接将null
强制转换为特定案例类的代码不起作用,并且不会引发错误,我对原因很感兴趣。
trait V {}
case class W(x: Int) extends V
val y = null.asInstanceOf[W]
y match {
case w:W => println("null cast to W is a W")
case _ => println("null cast to W is NOT a W")
}
// prints "null cast to W is NOT a W"
y match {
case v:V => println("null cast to W is a V")
case _ => println("null cast to W is NOT a V")
}
// prints "null cast to W is NOT a V"
val z = W(1)
z match {
case w:W => println("instantiated W is a W")
case _ => println("instantiated W is NOT a W")
}
// prints "instantiated W is a W"
z match {
case v:V => println("instantiated W is a V")
case _ => println("instantiated W is NOT a V")
}
// prints "instantiated W is a V"