5

Is it possible to define a value (in a if) in a for comprehension in Scala for use in yield.

I want to do this to avoid a potential expensive evaluation two times.

An example to illustrate.

for {
 bar <- bars if expensive(bar) > 5
} yield (bar, expensive(bar))
4

2 回答 2

7

How about this:

for {
 bar <- bars
 exp = expensive(bar)
 if exp > 5
} yield (bar, exp)
于 2012-11-09T19:39:17.937 回答
4

Yes, you can:

scala> List(1,2,3,4,5)
res0: List[Int] = List(1, 2, 3, 4, 5)

scala> for(n <- res0; val b = n % 2; if b==1) yield b
res2: List[Int] = List(1, 1, 1)
于 2012-11-09T19:39:03.540 回答