2

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?

dbc
  • 104,963
  • 20
  • 228
  • 340
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • _"which is why C# introduced optional value types"_ It's not the reason. – gdoron Mar 17 '12 at 23:18
  • 1
    This is one of the best explanations of why `Option` is better than `null`: [Why Scala's "Option" and Haskell's "Maybe" types will save you from null](http://james-iry.blogspot.com/2010/08/why-scalas-and-haskells-types-will-save.html) – Jesper Mar 18 '12 at 10:19

2 Answers2

5

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
Community
  • 1
  • 1
dhg
  • 52,383
  • 8
  • 123
  • 144
  • I know it's going on three years since you posted your answer, but FYI, I'm getting the following in the Scala 2.11.4 REPL: :11: error: type mismatch; found : List[Int], required: Option[?], for(x <- a; **y <- b**; z <- c) yield x + y + z – Brad Collins Dec 13 '14 at 03:24
  • fixed; it now compiles. – dhg Dec 13 '14 at 19:35
1

In C# (and in general in the .NET Framework) there is the type Nullable<T>, which is a kind of wrapper for value types.

Nullable<int> i = null;
if (i == null) ...
if (i.HasValue) { int k = i.Value; ... }

There is a shortcut for Nullable<T>: T?.

int? i = null;

On the other hand, there are optional parameters. You must define the default value of these. There is no way to know if they are missing.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188