Scala syntax for accessing the inline and chain "OrElse" option property?

Sometimes I want to return a value that is a property of an object wrapped in a parameter, but I cannot do it easily with getValue.orElse(otherValue) .

For example, I map inline properties, and I want to use a template like object.get.property.orElse("") . But the previous one does not compile. How can I access this property and maintain syntax like parameter?

+8
scala
source share
2 answers

You can use map() to achieve this. This becomes apparent when you start thinking of Option[T] as a container of type T , which can contain 0 or 1 elements:

 case class Person(name: String, age: Int) val optionalPerson = Some(Person("John", 29)) val name = optionalPerson map {_.name} getOrElse "?" 

Also, if you have a nested Option s structure:

 case class Person(name: String, age: Int, parent: Option[Person]) 

you can extract the nested Option using 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() to None when the value enclosed in Some does not satisfy some criteria:

 val nameIfAdult = optionalPerson filter {_.age >= 18} map {_.name} 
+12
source share

Use map() to save a template like this option.

For example, you need to get the name property of a field object. But if the field is really None , you can return an empty string. Like this:

field.map(_.name).getOrElse("")

And using it in a larger picture:

 implicit def castDraftModel(drafts:List[Tuple2[models.ReportInstance,Option[models.Report]]]) = drafts.map{ (field) => List(Field( field._1.id, field._1.teamId, field._2.map(_.name).getOrElse(""), field._1.lastModifiedRelative, field._2.map(_.id).getOrElse(0L), field._2.map(_.reportType).getOrElse(""), field._1.referenceId, field._1.referenceName( draft._2.map(_.reportType).getOrElse("") ) )) }.flatten.sortBy(_.id) 
+4
source share

All Articles