Scala's null
is the same as in Java. Any reference type can be null
, like Strings, Objects, or your own classes. Also just like Java, value types like Ints can't be null
.
Null is a trait whose only instance is null
. It is a subtype of all reference types, but not of value types. Its purpose in existing is to make it so reference types can be assigned null
and value types can't.
Nothing is a trait that is guaranteed to have zero instances. It is a subtype of all other types. It has two main reasons for existing: to provide a return type for methods that never return normally (i.e. a method that always throws an exception). The other reason is to provide a type for Nil (explained below).
Unit in Scala is the equivalent of void
in Java. It's used in a function's signature when that function doesn't return a value.
Nil is just an empty list, exactly like the result of List()
. It is of type List[Nothing]
. And since we know there are no instances of Nothing, we now have a list that is statically verifiable as empty. Nice to have.
An empty list can be represented by another nothing value: Nil
List() === Nil shouldBe res0
None is the counterpart to Some, used when you're using Scala's Option class to help avoid null
references.
None
equals None
:
None === None shouldBe res0
None
should be identical to None
:
None eq None shouldBe res0
None
can be converted to a String:
assert(None.toString === res0)
None
can be converted to an empty list:
None.toList === Nil shouldBe res0
None
is considered empty:
assert(None.isEmpty === res0)
None
can be cast to Any
, AnyRef
or AnyVal
:
None.asInstanceOf[Any] === None shouldBe res0
None.asInstanceOf[AnyRef] === None shouldBe res1
None.asInstanceOf[AnyVal] === None shouldBe res2
None
can be used with Option
instead of null references:
val optional: Option[String] = None
assert(optional.isEmpty === res0)
assert(optional === res1)
Some
is the opposite of None
for Option
types:
val optional: Option[String] = Some("Some Value")
assert((optional == None) === res0, "Some(value) should not equal None")
assert(optional.isEmpty === res1, "Some(value) should not be empty")
Option.getOrElse
can be used to provide a default in the case of None
:
val optional: Option[String] = Some("Some Value")
val optional2: Option[String] = None
assert(optional.getOrElse("No Value") === res0, "Should return the value in the option")
assert(optional2.getOrElse("No Value") === res1, "Should return the specified default value")