You can use map() to achieve this. It becomes obvious once you start to think about Option[T] like a container of type T that can hold 0 or 1 element:
case class Person(name: String, age: Int)
val optionalPerson = Some(Person("John", 29))
val name = optionalPerson map {_.name} getOrElse "?"
Furthermore if you have a nested structure of Options:
case class Person(name: String, age: Int, parent: Option[Person])
you can extract nested Option with flatMap:
val optionalPerson = Some(Person("John", 29, Some(Person("Mary", 55, None))))
val parentName = optionalPerson flatMap {_.parent} map {_.name} getOrElse "Unknown parent name" //Mary
Or you can use filter() to turn Some() into None when value wrapped in Some does not satisfy some criteria:
val nameIfAdult = optionalPerson filter {_.age >= 18} map {_.name}
answered 2012-06-26T17:09:52.147