Reading multiple variables from an object wrapped in Option[]

倾然丶 夕夏残阳落幕 提交于 2019-12-13 13:16:25

问题


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?


回答1:


How about this?

obj.map(_.var1).getOrElse("default1")

or, if you prefer this style:

obj map (_ var1) getOrElse "default"



回答2:


Another variation would be to use a version of the Null Object Pattern and use the object directly

//could also be val or lazy val
def myDefault = new MyObject {
  override val var1 = "default1"
  override val var2 = "default2"
}

val myObj = obj getOrElse myDefault

use(myObj.var1)
use(myObj.var2)



回答3:


To extract multiple values from an Option I'd recommend returning a tuple and using the extractor syntax:

val (val1, val2) = obj.map{o => (o.var1, o.var2)}.getOrElse(("default1", "default2"))


来源:https://stackoverflow.com/questions/7108087/reading-multiple-variables-from-an-object-wrapped-in-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!