1

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.

Artemis
  • 2,553
  • 7
  • 21
  • 36
Mandroid
  • 6,200
  • 12
  • 64
  • 134
  • It would be easier to help if you can provide example definitions of those types; also it is not clear what the final result should be. – Luis Miguel Mejía Suárez Mar 29 '21 at 14:16
  • 2
    Rather use `Option` combinators or pattern matching; e.g `(for { x <- A.x; y <- A.y } yield somethingWith(x, y)).getOrElse(defaultValue)` – cchantep Mar 29 '21 at 15:49

2 Answers2

4

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

The cleanest expression of this would be

A.x.map(x => A.y.fold(default_value)(y => calculation_using_y))
Tim
  • 26,753
  • 2
  • 16
  • 29