Scala: accessing an optional value in an optional object

Is there a good way to access a parameter value inside an Option object? Nested matches lead to an ugly tree structure.

So, if I have, for example:

case class MyObject(value: Option[Int])
val optionObject : Option[MyObject] = Some(MyObject(Some(2))

The only thing I know to access the value will be:

val defaultCase = 0 //represents the value when either of the two is None
optionObject match {
    case Some(o) => o.value match {
        case Some(number) => number
        case None => defaultCase
    }
    case None => defaultCase
}

And this is pretty ugly, because this design is only for access to one small parameter value.

What I would like to do is something like:

optionObject.value.getOrElse(0)

or how you can do with Swift :

if (val someVal = optionObject.value) {
   //if the value is something you can access it via someVal here
}

Is there anything in Scala that allows me to handle these things well?

Thank!

+4
source share
1 answer

flatMap "" . , ( ) Option Some, Some . getOrElse , Option.

optionObject.flatMap(_.value).getOrElse(0)
+6

All Articles