Вопрос

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)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top