I have a variable obj: Option[MyObject]
and want to extract multiple variables from it - if the object is not set, default values should be used.
Currently I do it like this:
val var1 = obj match {
case Some(o) => e.var1
case _ => "default1"
}
val var2 = obj match {
case Some(o) => e.var2
case _ => "default2"
}
...
which is extremely verbose. I know I could do it like this:
val var1 = if (obj.isDefined) obj.get.var1 else "default1"
val var2 = if (obj.isDefined) obj.get.var2 else "default2"
which still seems strange. I know I could use one big match and return a value object or tuple.
But what I would love is something similar to this:
val var1 = obj ? _.var1 : "default1"
val var2 = obj ? _.var2 : "default2"
Is this possible somehow?
How about this?
obj.map(_.var1).getOrElse("default1")
or, if you prefer this style:
obj map (_ var1) getOrElse "default"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With