null in Scala — Some Interesting Exploration

Mageswaran D
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 = null
scala> nullValue.toString
java.lang.NullPointerException
... 29 elided
scala> 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])
0
scala> println(null)
null
scala> def printit(x: Int) = println(x)
printit: (x: Int)Unit

scala> printit(null.asInstanceOf[Int])
0
scala> 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.

Written by

A simple guy in pursuit of of AI and Deep Learning with Big Data tools :) @ https://www.linkedin.com/in/mageswaran1989/

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade