scala:将 null 分配给原语 [英] scala: assign null to primitive
问题描述
我试图将 null 分配给一个像这样的 Double 变量:
I am trying to assign null to a variable which is Double like this:
var foo = 0.0
foo = null
然而,这会导致 null 不能隐式转换为 Double 的错误
However, this gives an error that null cannot be implicitly converted to Double
所以我改为这样做:
foo = null.asInstanceOf[Double]
然而 foo 的新值是 0.0
however the new value for foo is 0.0
如何将值设置为空?
推荐答案
你不能.Double
是值类型,你只能将 null
赋值给引用类型.相反,Scala 编译器将 null
替换为默认值 0.0.
You can't. Double
is a value type, and you can only assign null
to reference types. Instead, the Scala compiler replaces null
with a default value of 0.0.
查看 SLS 4.2:
default type
0 Int or one of its subrange types
0L Long
0.0f Float
0.0d Double
false Boolean
您也不能将 Java 原语分配给 null
.虽然 Scala 的 Double
并不是真正的原始类型(它实际上是 Scala 中的一个类),但它需要编译为 Java 字节码中的 double
.相反,如果你想表示一个完全缺失的值,你应该使用 Option[Double]
,并尝试 never 在 Scala 中使用 null
.
You cannot assign Java primitives to null
, either. And while Scala's Double
isn't truly a primitive (it is actually a class in Scala), it needs to compile down to double
in Java byte code. Instead, you should use Option[Double]
if you want to represent a value that is missing entirely, and try to never use null
in Scala.
这篇关于scala:将 null 分配给原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!