Reputation: 7488
I have an Option instance, say O, which contains an instance of a class, say A, and A itself has some Options inside it.
I have to achieve something like this, expressed in pseudo code as:
if(A.x exists) {
if(A.y exists) {
//extract values from some another Option Z embedded in A
} else {
// return Option of some default value
}
}
So I try this:
O.filter(some filter condition to have only some specific types of A).filter(!A.x.isEmpty).filter(!A.y.isEmpty).flatMap(_.z.somevalue).orElse(Some("Some default value"))
Is this the correct way, OR do I need to use pattern matching at some point?
Edit: Result should be an Option[String].O si an Option[A]. A is a class with fields x,y,z, and all three are Option of String.
Upvotes: 1
Views: 933
Reputation: 27356
The cleanest expression of this would be
A.x.map(x => A.y.fold(default_value)(y => calculation_using_y))
Upvotes: 0
Reputation: 22850
This looks like a good use case for pattern matching.
For what I understood of your question you want something like this:
(if not, the code should be easy to adjust)
final case class A(x: Option[String], x: Option[String], x: Option[String])
def getData(oa: Option[A]): Option[String] = oa match {
case Some(A(Some(_), Some(_), z)) => z
case None => None
case _ => Some("Default Value")
}
Upvotes: 4