从编写惯用代码,高效代码等角度判断它。
我有以下定义的多种方式从getConf1,getConf2或getConf3获取conf值,无论哪个成功地按照该顺序调用时产生一个值。换句话说,如果getConf1产生一个值,我们将跳过剩下的两个。如果getConf1没有产生值,那么我们将尝试getConf2,依此类推。
def getConf1(name: String): Option[String]
def getConf2(name: String): Option[String]
def getConf3(name: String): Option[String]
方法1:
def getSetting(name: String): Option[String] = {
var r = getConf1(name)
if(!r.isDefined) {
r = getConf2(name)
}
if(!r.isDefined) {
r getConf3(name)
}
r
}
方法2:
def getSetting(name: String): Option[String] = {
val val1 = getConf1(name)
val val2 = getConf2(name)
val val3 = getConf3(name)
(val1, val2, val3) match {
case (a: Some[String], _, _) => a
case (_, a: Some[String], _) => a
case (_, _, a: Some[String]) => a
case _ => None
}
}
方法3:
def getSetting(name: String): Option[String] = {
val myList = List(
(n:String) => getVal1(n),
(n:String) => getVal2(n),
(n:String) => getVal3(n))
doConditionally(name, myList)
}
def doConditionally[T1, T2](name: T1, list: List[(T1) => Option[T2]]): Option[T2] = {
list match {
case h::t =>
val r = h(name)
if(r.isEmpty) {
doConditionally(name, t)
} else {
r
}
case Nil =>
None
}
}
答案 0 :(得分:11)
与orElse
链接:
getConf1(name).orElse(getConf2(name)).orElse(getConf3(name))
请注意getConf2
和getConf3
仅如果链到达None
时会被<{1}}调用(它们会被懒惰地评估)。
答案 1 :(得分:2)
附注,找到提供值的第一个函数,
Seq(getConf1 _, getConf2 _, getConf3 _).find(_("aName").isDefined)