假设我有这样的功能:
def foo(x: Int): Int = ???
def bar(xs: List[Int]): List[Int] = xs map {
case x if (x > 0) => x
case x if (foo(x) > 0) => foo(x) + 1
case _ => 0
}
问题是foo
被称为两次。您如何撰写bar
仅拨打foo
一次?
答案 0 :(得分:5)
def foo(x: Int): Int = ???
def bar(xs: List[Int]): List[Int] = xs.map {
x =>
lazy val food = foo(x)
if(x > 0) x
else if (food > 0) food + 1
else 0
}
答案 1 :(得分:4)
case x =>
val y = foo(x)
if(y > 0) y + 1 else 0
或map
两次:
list
.map {
case x if x > 0 => x
case x => foo(x) + 1
}.map {
case x if x < 0 => 0
case x => x
}
或者将foo包装到Option
,并过滤:
...
case x => Option(foo(x) + 1).filterNot(_ < 0).getOrElse(0)