Search code examples
scalascala-option

Using Option in functional way to avoid if-else


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.


Solution

  • 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")
    }