Filtering with if
Guards in comprehensions.
Guards in for-comprehensions
Inside a for-comprehension you can add an if condition called a guard. It keeps only the elements that satisfy the condition, just like filter.
object Main {
def main(args: Array[String]): Unit = {
val evens = for (x <- 1 to 10 if x % 2 == 0) yield x
println(evens)
}
}Guards desugar to withFilter
A guard if cond is rewritten into a call to withFilter (a lazy variant of filter).
for (x <- xs if p(x)) yield x- becomes
xs.withFilter(p).map(x => x)
object Main {
def main(args: Array[String]): Unit = {
val sugar = for (x <- List(1, 2, 3, 4) if x > 2) yield x
val desugared = List(1, 2, 3, 4).withFilter(_ > 2).map(x => x)
println(sugar == desugared)
}
}All lessons in this course
- Desugaring for
- Filtering with if
- Multiple Generators
- Using with Option and Future