在Scala中将null转换为case类的实例

我有一段代码依赖于某个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"

lchfeiniao 回答:在Scala中将null转换为case类的实例

铸造会更改编译时类型,而不是运行时类型。模式匹配检查运行时类型。实际上,案例类模式匹配甚至具有对null的显式检查。请参阅Why is there a `null` check in the implementation of the `unapply` method for case classes?(由于使用类型模式,该检查不会影响您的情况)。

此外,即使不是因为模式匹配问题,也无法在没有得到NullPointerException的情况下“在类的字段上进行操作”。

,

由于Type Patterns的定义如下:

  
      
  • 对类Cp.CT#C的引用。此类型模式匹配给定类的任何非空实例。
  •   

因此:null是类型W的完全有效值;但不会与模式w: W相匹配。

与之不匹配的主要原因就是

  
    

我有一段代码依赖于某个case类的任意元素的存在,以便在该类的字段上进行操作。

  

因此,当您与w: W匹配时,您想知道其字段和方法可用。但是对于null来说不是。

本文链接:https://www.f2er.com/3119556.html

大家都在问