Scala: Access optional value in optional object
Asked Answered
S

1

7

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!

Saltwort answered 7/3, 2015 at 9:13 Comment(0)
P
9

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)
Plover answered 7/3, 2015 at 9:18 Comment(5)
Quite nice, but if the nesting is deeper it would expand to: optionObject.flatMap(_.value).flatMap(_.someOther).flatMap(_.another).getOrElse(0) right? This is way better than the match nesting but a little syntactic sugar could be applied..Saltwort
For-comprehension is useful: val v: Option[String] = for { someVal1 <- opt1; val2 <- someVal1.optProp; val3 <- val2.optProp } yield val3Covered
I thought about for comprehensions, but in this case they just make the code twice as long...Plover
Great to see both options of cchantep and and KimStebel. Cause it depends on the amount of nesting and so on you want to do which way is nicerSaltwort
The best post I've seen regarding various idomatic ways of working with Options is this: blog.originate.com/blog/2014/06/15/…. Depending on your background and coding standards, some may fight your need and match your existing code base better than others, but it's worth noting the various ways in which you can interact with Options.Tori

© 2022 - 2024 — McMap. All rights reserved.