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))
How about this:
for {
bar <- bars
exp = expensive(bar)
if exp > 5
} yield (bar, exp)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With