Alex Rivera | Logout

Scala syntax to access property of an option inline and chain "OrElse"?

Asked 2012-06-26T17:06:51.333
14

Sometimes I want to return the value that is a property of an object wrapped in option, but I can't do that easily with getValue.orElse(otherValue).

For instance, I am mapping properties inline and I want to use a pattern like object.get.property.orElse(""). But the preceding doesn't compile. How can I access that property and still maintain an option-like syntax?

Edit
Report

1 Answer

18

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

Your Answer