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!
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