Scala Nothing and Null Data Types

In this tutorial, we will learn about the Nothing and Null data types in Scala with examples. By Shivang Yadav Last updated : April 02, 2023

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(none) // gives error : not found : value none 




Scala Example of None Type

object MyClass {
    def main(args: Array[String]) {
         //printing empty list
        //checking whether None is empty or not
        //printing value of None as string




Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.