Empty values in Scala

Data centre
Reading Time: 3 minutes

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.

scala

Null Type

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 reference

null is the instance of Null. It can be used to show that reference type values are empty.

None

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.

scala none

The output of the above code is

scala none

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.

Scala Unit code

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

Scala output unit

Nil

Nil can be considered as an empty List or simply you can say a List with zero elements inside it.

Scala nil

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.

Scala nil output

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.

Scala type hierarchy

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

https://blog.rockthejvm.com/

knoldus scala dept.

Written by 

Divyansh Devrani is a Software Consultant having experience in the Scala Ecosystem. He has worked on technologies like Scala, Akka, Play, and Postgre. He is recognized as a good team player who wants to interact with new technologies. He loves to learn new things His hobbies include listening to muisc, watching movies and anime.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading