Why in Scala Long cannot in initialized to null wh

2019-02-09 19:30发布

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.

3条回答
我想做一个坏孩纸
2楼-- · 2019-02-09 20:08

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 types hierarchy

查看更多
别忘想泡老子
3楼-- · 2019-02-09 20:17

Scala Long is literal date 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

查看更多
We Are One
4楼-- · 2019-02-09 20:18

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.

查看更多
登录 后发表回答