Nothing and Null
Nothing
Nothing is a subclassify of all value types, it is also called the bottom type. Type Nothing That has no value.
- In Nothing you can’t create an instance of it or assign it to any variable.
- It has zero instances.
- One of the reasons to use Nothing is to provide a return type for the functions that never return i.e. a method which always throws an exception.
- Nothing used as a return type for the operations that doesn’t return a value.
- We can use Nothing to signal non-termination such as a thrown exception, program exit, or an infinite loop .
Null
Null is a subclassify of all reference types. the keyword literal null can identify a single value.
- Null class is a child of all reference classes. But generally speaking, you should try to avoid using Null in typical Scala programming.
- Using Scala’s literal keyword “null”, you can assign a Null to any reference class.
- Null is provided mostly for interoperability with other JVM languages.
Scala Type Hierarchy
There are no primitive types in Scala(unlike Java). All data types in Scala are objects that have methods to operate on their data. All of Scala’s types exist as part of a type hierarchy. Every class that we define in Scala will also belong to this hierarchy automatically.
Any
Any is the superclass of all classes, also called the top class. It defines certain universal methods such as equals, hashCode, and toString. Any has two direct subclasses:
- AnyVal
- AnyRef
Example:
Scala
// Scala program of Scala Type hierarchy // Creating object object Geeks { // Main method def main(args : Array[String]) { val list : List[Any] = List( false , 66677 , 732 , 'a' , "abs" ) list.foreach(element = > println(element)) } } |
Output
false 66677 732 a abs