How about this:
for {
bar <- bars
exp = expensive(bar)
if exp > 5
} yield (bar, exp)
Question
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))
La solution
How about this:
for {
bar <- bars
exp = expensive(bar)
if exp > 5
} yield (bar, exp)
Autres conseils
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)