There are different values in scala which we used as empty values. In this blog, we are going to discuss these empty values like what are these values, how to use them, etc.
Null extends all the reference types even the classes and traits which are defined by us. We can assign Null to the reference type (List, Option, etc) but not to the value type (Int, etc). It has only one instance i.e. null.
null is the instance of Null. It can be used to show that reference type values are empty.
In Scala, we commonly use Options, which is a data structure. Option has two subclasses one of them is Some and the other one is None. None is used as a return value to avoid null pointer exceptions. Let’s see how none works.
The output of the above code is
As we can see the variable “some” was having some value but the variable “none” was empty and hence it returns None.
Unit in scala
In scala, Unit is equivalent to void. Unit is the return type of a function when the function has no value to return.
As you can see from the code in the above image that the method Print() is returning no value hence its return type is Unit. The output of the above code is
Nil can be considered as an empty List or simply you can say a List with zero elements inside it.
As you can see in the above code we are trying to print Nil. Here our method PracticeNil() has no value to return and hence its return type is Unit. Now, let’s check what will be the output of this code.
As you can see here we are getting an empty List as an output which shows that Nil is an empty value used for an empty List.
Nothing in scala
Nothing in scala is the subtype of every type. it is used for the return type of the piece of code that can affect the flow of the program.
The above image is showing type hierarchy in scale and it shows that Nothing is the subtype of every type ( including Unit, Null, etc).
Conclusion of this blog
We get to know about different types of empty values in scala i.e. Nothing, Null, Nil, Unit, None.
For more tech blogs follow: KNOLDUS BLOGS