I am creating my Scala bean which is a configuration to be loaded from a YML config. I want a long property to be null if not specified, but I'm facing below issue. Any idea why?
startOffset: Integer = null
scala> var endOffset: Long = null
<console>:11: error: an expression of type Null is ineligible for implicit conversion
var endOffset: Long = null
^`
PS: Yes I can use Option[Long]
but wanted clarity and is there anything wrong with this approach.
In Scala, type
scala.Null
is a subtype of all reference types (all types which inherit fromscala.AnyRef
- which is an alias ofjava.lang.Object
). That's why you can use thenull
value (of typescala.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 asscala.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 isjava.lang.Integer
, which is a subtype ofjava.lang.Object
(a.k.a.scala.AnyRef
): it's a reference type, so you can usenull
.It's probably easier to understand with this diagram of the Scala type hierarchy (lifted from the official documentation):
Scala
Long
is literal date type likelong
in Java. Same is true forInt
. ButInteger
is a Wrapper class i.ejava.lang.Integer
If you want nullable Long value, you can use
java.lang.Long
Int
andLong
are Scala types and are derived fromAnyVal
, which is not a reference type (i.e. notAnyRef
) and hence can't benull
.Integer
on the other hand is an alias forjava.lang.Integer
, which is a reference type.No, it's not an oversight,
Int
andLong
are consistent, usingnull
in Scala is considered a bad thing and, as I understand it,null
exists merely for Java compatibility (even forAnyRef
) as well asInteger
.