Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you define a value (in a if) in a for comprehension in Scala for use in yield

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))
like image 921
Farmor Avatar asked Nov 09 '12 19:11

Farmor


2 Answers

How about this:

for {
 bar <- bars
 exp = expensive(bar)
 if exp > 5
} yield (bar, exp)
like image 185
Don Avatar answered Nov 15 '22 04:11

Don


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)
like image 34
pedrofurla Avatar answered Nov 15 '22 02:11

pedrofurla