Created
June 6, 2014 16:51
-
-
Save ClintCombs/9648cb77787feebe145e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
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
Note that you can call foreach on an Option[T] and it is treated like a collection of zero or one items.