您可以在Scala中为for comprehension定义一个值(在if中)以用于yield

Far*_*mor 5 functional-programming scala for-comprehension

是否可以在Scala中为for comprehension定义一个值(在if中)以用于yield.

我想这样做是为了避免两次潜在的昂贵评估.

举例说明.

for {
 bar <- bars if expensive(bar) > 5
} yield (bar, expensive(bar))
Run Code Online (Sandbox Code Playgroud)

Don*_*Don 7

这个怎么样:

for {
 bar <- bars
 exp = expensive(bar)
 if exp > 5
} yield (bar, exp)
Run Code Online (Sandbox Code Playgroud)