null in Scala — Some Interesting Exploration
Sep 5, 2018 · 1 min read
abstract final class Null extends AnyRef
In Scala Null is a type, which has a single value null. Since null is a value and every value in Scala is an object, you can call few methods on it.
scala> val nullValue = null
nullValue: Null = nullscala> nullValue.toString
java.lang.NullPointerException
... 29 elidedscala> nullValue.map
<console>:13: error: value map is not a member of Null
nullValue.map
What happens if nullis type casted to Int?
scala> println(null.asInstanceOf[Int])
0scala> println(null)
nullscala> def printit(x: Int) = println(x)
printit: (x: Int)Unit
scala> printit(null.asInstanceOf[Int])
0scala> printit(null)
<console>:13: error: an expression of type Null is ineligible for implicit conversion
printit(null)scala> def nullint[T] = null.asInstanceOf[T]
nullint: [T]=> T
scala> println(nullint[Int])
null
scala> def nullspecint[@specialized(Int) T] = null.asInstanceOf[T]
nullspecint: [T]=> T
scala> println(nullspecint[Int])
0
Even though the nullis type casted as Int (null.asInstanceOf[Int]) compiler considers it as a primitive type and hence converts the referencenullis converted to default value 0. Reason for this behavior is its boxed as Integer with value as null.
If a generic method does this cast, then, naturally, you get a null back.
