Search code examples
c#scalanullnullablescala-option

optional references types


Possible Duplicate:
Why Option[T]?

Reference types provide the special value null meaning "absence of a value". Value types have no such value, which is why C# introduced optional value types (along with special syntax for them).

Scala's Option[T] has three different "null" values: null, None and Some(null). What exactly does this added complexity buy us in terms of safety and expressibility? When would I use which?


Solution

  • Good Scala really only has one null value: None. Don't use null (except for backward compatibility with existing Java code).

    There are many answers on SO regarding why Option[T] is useful. For example: see this.

    The short version:

    It makes the optional nature a signature explicit. The following clearly states that we expect that t could be "null":

    def f(t: Option[T]) 
    

    You don't have to null-check before operations: (i: Option[Int]) => i.map(_ + 1) works fine whether i is Some(5) or None, and preserves the Option wrapper to indicate that the input could have been None (and, thus, the output might be None as well).

    def f(i: Option[Int]) = i.map(_ + 1)
    f(Some(5)) // Some(6)
    f(None)    // None
    

    You can compose them easily with other Options or collections:

    val a: Option[Int] = Some(1)
    val b: Option[Int] = Some(6)
    val c: Option[Int] = Some(5)
    val d: Option[Int] = None
    for(x <- a; y <- b; z <- c) yield x + y + z // Some(12)
    for(x <- a; y <- d; z <- c) yield x + y + z // None