Option in Scala
Fall 2011, David Matuszek


Syntax errors are better than runtime errors, because (1) you get them right away, not some arbitrary time later, and (2) the fix is usually obvious.

Sometimes you might or might not have a value. You search a list, and find or don't find something. You ask the user to choose a file, and the user clicks the Cancel button. You try to look up something in a HashMap, and it isn't there. Et cetera. In these situations, Java typically returns the value null to indicate "nothing found." If you don't always check for null, you may get a NullPointerException.

Scala has a null value in order to communicate with Java, and you should use it only for this purpose. Everyplace else, you should use Option. With Option, you may make syntax errors, but you will never get a NullPointerException.

Option adds some complexity to your program, so don't use it unnecessarily. If you can arrange your code so that your variables always have a value, that's better. But if you might or might not have a value, use Option.

Technical details

Option is a parameterized type: For example, you can have an Option[String], or an Option[File].

The value of an Option[type] variable is either Some(value of the correct type) or None. For example,

    var s = Some("abc")          // Scala can infer the type
    var t: Option[String] = None // Type must be explicit

    def chooseFile(): Option[File] = { ... }

The most general way to use an Option is with a match:

    chooseFile() match {
      case Some(f) => // Do something with file f
      case None =>    // Do something when there is no file

You can check if an Option value is defined by comparing it with None, or by using the isDefined or isEmpty method:

    if (t isDefined) println(t)
    if (t isEmpty) println("Nothing here!")

You can extract the value of an Option, but only if you provide some default value for the None case:

    val w = t.getOrElse("Nothing here!")

If you apply the toList method to an Option (val myList = t.toList), you will get either an empty list (for None), or a list containing one value.

List functions such as map and filter may be applied to an Option, and the Option will be treated as a list containing zero or one elements; the result will still be an Option. For example:

    t = Some("SoyaWannaBurger")
println(t map(_.toString) filter(_.length > 0) map(_.toUpperCase)) // Prints: Some(SOYAWANNABURGER)

Additional Option methods may be found in the Scala API.