10/18/2012

Null, null, Nil, Nothing, None, and Unit in Scala

Null- is a subtype of all reference types; its only instance is the null reference. Since Null is not a subtype of value types, null is not a member of any such type.
null- Is an only instance of Null. Similar to Java null.
Nil- Represents an emptry List of anything of zero length. Its not that it refers to nothing but it refers to List which has no contents.
Nothing is a subtype of every other type (including scala.Null); there exist no instances of this type.
None This case object represents non-existent values. Just to avoid null pointer exception. Option has exactly 2 subclasses- Some and None. None signifies no result from the method.
Unit - There is only one value of type Unit, (), and it is not represented by any object in the underlying runtime system. A method with return type Unit is analogous to a Java method which is declared void.
Note: Any is supertype of AnyRef and AnyVal. AnyRef is the supertype of all the reference classes (like String, List, Iterable) in scala. AnyVal is the supertype of all the value classes (like Int, Float, Double, Byte, Short..). Null is a subtype of all the reference classes. null is its only instance. Nothing is subtype of every other type i.e of reference and value classes.
Think- AnyRef == Object in Java.
The above is a breif summary of a wonderful post by Matt Malone where he has explained all these concepts in depth with examples. Read the blog post here.

2 comments:

  1. hipy said...

    Null is not a trait

    Yeah,
    as of http://www.scala-lang.org/api/2.7.6/scala/Null.html is IS a trait, however currently it is NOT:
    http://www.scala-lang.org/api/2.10.4/#scala.Null

    ReplyDelete