Scala is a flexible language and it is heavily utilized by various frameworks such as Apache Spark, Apache Kafka. It is interoperable with Java and relies heavily on JVM, for now.
The creator of Scala, Martin Odersky called null
as “The Million Dollar Mistake”, this pegs the question - how does Scala deal with emptiness? Is it any better than Java? To formulate an opinion for that question we have to know about four classes that can be used in Scala to convey the lack of a value – Nil, None, Nothing, Null.
Nil object Nil extends List[Nothing] with Product with Serializable
An empty immutable List()
scala> Nil
res0: scala.collection.immutable.Nil.type = List()
None object None extends Option[Nothing] with Product with Serializable
A class used to represent lack of value, mostly used with return
to avoid NullPointerException
Example:
val myValue: Option[String] = | myValue.getOrElse("DoesNotExist") |
---|---|
Some("token") | res0: String = token |
None | res1: String = DoesNotExist |
null | java.lang.NullPointerException |
Nothing abstract final class Nothing extends Any
There are no instances of this type and it is an subtype of every other type.
“Another usage for Nothing is the return type for methods which never return normally. One example is method error in scala.sys, which always throws an exception.” – Scala API docs
scala> List()
res0: List[Nothing] = List()
Null abstract final class Null extends AnyRef
A Scala trait with null
as is its only instance.
scala> null
res0: Null = null