Reading — step 1 of 5
Learn
~1 min readEffect Types
For-comprehensions are syntax sugar for chained map, flatMap, and filter. They make nested operations on "box" types readable.
Without for-comp:
result1.flatMap { a =>
result2(a).flatMap { b =>
result3(a, b).map { c =>
c + a
}
}
}
With for-comp:
for {
a <- result1
b <- result2(a)
c <- result3(a, b)
} yield c + a
Same syntax works for any "box" type that has map/flatMap:
Option,Try,Either,Future,List,Vector, custom monads
With filter (only for types where withFilter makes sense):
for {
n <- 1 to 10
if n % 2 == 0
sq = n * n // local binding (not a generator)
} yield sq
// Vector(4, 16, 36, 64, 100)
Multiple generators give Cartesian products — like nested loops:
for {
x <- 1 to 3
y <- 1 to 3
if x != y
} yield (x, y)
// pairs where x != y
Without yield — just runs side effects:
for (line <- io.Source.stdin.getLines()) {
println(line.toUpperCase)
}
For-comprehensions are how Scala folds nested logic flat. Whenever you see 3+ levels of nested flatMap, switch to a for-comp.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…