There are multiple constructs to represent Emptiness in Scala.
a. null
b. Null
c. Nothing
d. Nil
e. None
f. Unit
null
It is same as null in Java. All reference types in Scala can be assigned with null, but not the value types.
Example
var x : String = null
scala> var x : String = null
var x: String = null
scala> if(x == null) println("x is null") else println("x is not null")
x is null
You can’t assign a null to value type variables.
scala> var y : Int = null
^
error: an expression of type Null is ineligible for implicit conversion
Null
Null is a trait, means it is a type not a value. It is a subtype of every type except those of value classes.
Null is the type of null. Nothingness for the references can be specified using Null type.
Just to confirm, Null (with capital N) is a type whereas null (with small n) is a value.
Nothing
Nothing is a trait, means it is a type not a value.
Example
scala> var emptyMap = Map()
var emptyMap: scala.collection.immutable.Map[Nothing,Nothing] = Map()
When you create an empty collection, the type of the collection is Nothing.
Nothing is a subtype of both AnyVal and AnyRef.
Nil
Nil is a special value associated with List class. Nil is a singleton object of type List[Nothing].
scala> Nil
val res0: scala.collection.immutable.Nil.type = List()
Why Nil?
Lists in Scala are implemented as LinkedList. Nil is used to represent end of the list.
None
None is a special value associated with an Option collection. Option collection is used to represent presence or absence of a value. It is similar to java.util.Optional class.
scala> def div(a: Int, b: Int) : Option[Int]
| = {
| if(b == 0) None
| else Option(a / b)
| }
def div(a: Int, b: Int): Option[Int]
If b is 0, the div function return None, else it return Option[Int]
Unit
Unit is similar to void in Java.
scala> def sayHello(): Unit= {println("Hello!!!!")}
def sayHello(): Unit
scala> sayHello()
Hello!!!!
No comments:
Post a Comment