Why in Scala Long cannot in initialized to null whear as Integer can
Int
and Long
are Scala types and are derived from AnyVal
, which is not a reference type (i.e. not AnyRef
) and hence can't be null
. Integer
on the other hand is an alias for java.lang.Integer
, which is a reference type.
No, it's not an oversight, Int
and Long
are consistent, using null
in Scala is considered a bad thing and, as I understand it, null
exists merely for Java compatibility (even for AnyRef
) as well as Integer
.
In Scala, type scala.Null
is a subtype of all reference types (all types which inherit from scala.AnyRef
- which is an alias of java.lang.Object
). That's why you can use the null
value (of type scala.Null
) anywhere a reference type is expected.
It is not, however, a subtype of any value type (types which inherit from scala.AnyVal
). Because types such as scala.Int
, scala.Long
, scala.Boolean
... (corresponding to Java's primitive types) are value types, they cannot be null.
As for the Integer
type you mention: I guess this is java.lang.Integer
, which is a subtype of java.lang.Object
(a.k.a. scala.AnyRef
): it's a reference type, so you can use null
.
It's probably easier to understand with this diagram of the Scala type hierarchy (lifted from the official documentation):
Scala Long
is literal data type like long
in Java. Same is true for Int
.
But Integer
is a Wrapper class i.e java.lang.Integer
If you want nullable Long value, you can use java.lang.Long