Home »
Scala
Scala Nothing and Null Data Types
By IncludeHelp Last updated : October 07, 2024
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.
Scala Example of null and Nil Types
object MyClass {
def main(args: Array[String]) {
println(null);
//println(none) // gives error : not found : value none
println(Nil)
}
}
Output
null
List()
Scala Example of None Type
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