Option and getOrElse in Scala

An Option can be thought of as a container (or proxy) for an object to prevent null pointer exceptions.

The paradigmatic case is returning an Option type from function calls, instantiated by either a Some or None subclass:

def toInt(in: String): Option[Int] = {
    try {
        Some(Integer.parseInt(in.trim))
    } catch {
        case e: NumberFormatException =>; None
    }
}

Some or None can be matched to functions by consumers:

toInt(someString) match {
    case Some(i) =>; println(i)
    case None =>; println("That didn't work.")
}

Say we have this type:

case class Person(age: Int)

In the case where it has a value:

val person = Option(Person(100))   > subclass Some
val age = person.map(_.age +5)     > Some(105)
age.getOrElse(0)                   > 105

In the case where it has no value:

val person = Option[Person] = Option(null)          > None
val age = person.map(_.age +5)                      > None
age.getOrElse(0)                                    > 0

You can see how getOrElse specifically requires the developer to specify the action for the null case.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s