Home »
Scala language
Nothing and Null Types in Scala
Scala Nothing and Null Types: Nothing and null are the value returned when no other value is returned by the program. In this Scala tutorial on nothing and null types we will learn about Scala nothing and null, nill types.
Submitted by Shivang Yadav, on July 22, 2019
Scala Nothing Type
It is a trait in Scala. Being a trait it does not have any instance, and is contained by every data set but is not a superclass. Nothing has found uses in functions that always return an exception to handle.
Scala Nil Type
It is a list that has no element. Nil uses nothing as it is a subset. Nil's type is list[nothing].
var a = nil gives a lit[nothing]
Scala Null Type
It is a trait that is used only by reference instances, not data instances. This means it is a subset of only reference class. Scala uses Option instead of Null as it is more effective. The value of the reference data types like objects etc is null, but this value is not valid for data types like Int, Float, etc.
Scala None Type
It is the replacement of null in the option type of Scala. It has none that is initialized when no value is given.
Example:
object MyClass {
def main(args: Array[String]) {
println(null);
//println(none) // gives error : not found : value none
println(Nil)
}
}
Output
null
List()
Example of None in Scala
object MyClass {
def main(args: Array[String]) {
//printing empty list
println(None.toList)
//checking whether None is empty or not
println(None.isEmpty)
//printing value of None as string
println(None.toString)
}
}
Output
List()
true
None