Skip to content

Instantly share code, notes, and snippets.

@ClintCombs
Created June 6, 2014 16:51
Show Gist options
  • Save ClintCombs/9648cb77787feebe145e to your computer and use it in GitHub Desktop.
Save ClintCombs/9648cb77787feebe145e to your computer and use it in GitHub Desktop.
scala> case class Girl(name: String, age: Option[Int] = None)
defined class Girl
scala> Girl(name = "Sue")
res7: Girl = Girl(Sue,None)
scala> Girl(name = "Betty", age = Some(29))
res8: Girl = Girl(Betty,Some(29))
scala> res8.age match {
| case Some(a) => s"$a years old"
| case None => "no idea how old she is"
| }
res9: String = 29 years old
scala> res8.age foreach { a => println(s"$a years on the planet") }
29 years on the planet
scala> val g3 = Girl("Lynn")
g3: Girl = Girl(Lynn,None)
scala> g3.age foreach { a => println(s"$a years on the planet") }
scala>
@ClintCombs
Copy link
Author

Note that you can call foreach on an Option[T] and it is treated like a collection of zero or one items.

@ClintCombs
Copy link
Author

Java 8's http://docs.oracle.com/javase/8/docs/api/java/util/Optional.html is a less useful version of Scala's Option.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment