Skip to main content

for comprehension

If a type has flatMap and map (or it has flatMap and map as its extension methods), you can use for comprehension instead of using nested flatMaps and map.

flatMap and map

In for comprehension, <-s (left arrows) are flatMap except for the last one. The last <- is map.

for {
b <- foo(a)
c <- bar(b)
d <- baz(c)
} yield a + b + c + d

is equivalent to

foo(a).flatMap { b =>
bar(b).flatMap { c =>
baz(c).map { d =>
a + b + c + d
}
}
}

for {
b <- foo(a)
c <- bar(b)
} yield a + b + c

is equivalent to

foo(a).flatMap { b =>
bar(b).map { c =>
a + b + c
}
}

for {
b <- foo(a)
} yield a + b

is equivalent to

foo(a).map { b =>
a + b
}

So the following one is meaningless

for {
b <- foo(a)
} yield b

because it's equivalent to

foo(a).map { b =>
b
}

which does nothing.

So you can simply do this instead.

foo(a)