Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Access optional value in optional object

Is there a good way to access a Option Value inside a Option Object? The nested match cases result in a 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 way I know to access the value would 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 quite ugly as this construct is just for accessing one little Option value.

What I would like to do is something like:

optionObject.value.getOrElse(0)

or like you can do with Swift:

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

Is there something in Scala that allows me to handle these things nicely?

Thanks!

like image 425
lukaswelte Avatar asked Mar 07 '15 09:03

lukaswelte


1 Answers

flatMap will let you map an Option and "flatten" the result. So if (and only if) the outer and the inner Option are both Some, you will get a Some with your value in it. You can then call getOrElse on it as you would do with any other Option.

optionObject.flatMap(_.value).getOrElse(0)
like image 171
Kim Stebel Avatar answered Oct 02 '22 14:10

Kim Stebel