Scala Option, Some, None syntax examples

Today I’m sharing some examples of the Scala Option/Some/None syntax. These examples will show how to use an Option for the var fields in a Scala class. Then I’ll show how to set those Option fields, and then get the values from the Option fields.

To get started, we’ll need a little case class to represent an Address:

case class Address (city: String, state: String, zip: String)

Next, we’ll create a User class that defines three Option fields. Two are of type String, one is of type Address:

class User(email: String, password: String) {
  var firstName = None: Option[String]
  var lastName = None: Option[String]
  var address = None: Option[Address]
}

That example shows how to define Scala Option fields when they have no initial value.

Personally, I can never remember this syntax, which is my main reason for sharing these examples today:

var firstName = None: Option[String]
var address = None: Option[Address]

This syntax says that these fields are Option fields of the specified types, and they’re initialized to the value None.

Populating (setting) Option fields, and getting Option values

Next, the following test object shows how to populate each Option field, and then use the resulting Some or None values in your application:

object Test extends App {

  // populate the object
  val u = new User("al@example.com", "secret")
  u.firstName = Some("Al")
  u.lastName = Some("Alexander")
  u.address = Some(Address("Talkeetna", "AK", "99676"))

  // print the object information
  println(s"First Name: ${u.firstName.getOrElse("not assigned")}")
  println(s"Last Name:  ${u.lastName.getOrElse("not assigned")}")
  u.address.foreach { a =>
    println(a.city)
    println(a.state)
    println(a.zip)
  }

}

Using Option as a constructor or method parameter

If you want to use an Option field as a constructor or method parameter, use the syntax shown in these examples:

scala> class Person(var firstName: String, var lastName: String, var mi: Option[String])
defined class Person

scala> val p = new Person("John", "Doe", None)
p: Person = Person@6ce3044f

scala> p.firstName
res0: String = John

scala> p.lastName
res1: String = Doe


// access the middle initial field while it's set to None
scala> p.mi
res2: Option[String] = None

scala> p.mi.getOrElse("(not given)")
res3: String = (not given)


// set the middle initial field, and access it again
scala> p.mi = Some("L")
p.mi: Option[String] = Some(L)

scala> p.mi.getOrElse("(not given)")
res4: String = L

Scaladoc

Here are links to the Scaladoc for the Option, Some, and None types:

Summary

I hope these examples of using the Scala Option, Some, and None syntax have been helpful. If you’d like to see other syntax examples, leave a note in the Comments section below.