Scala: for-comprehension stops at the empty box

Learn
1 min readJan 27, 2022

A for-comprehension is a stylized version of map function. A for comprehension with a bunch of left arrows is about happily opening boxes and applying functionalities on the values in the boxes. What happens when one of those boxes is empty?

Execution stops. The lines after the empty box does not execute at all. Something to keep in mind while you sequence your operations in your for-comprehension.

Let us look at a quick demonstration of this below.

def someA = {
println("someA")
Some("A")
}
def someB = {
println("someB")
Some("B")
}
def someC = {
println("someC")
Some("C")
}
def someD = {
println("someD")
Some("D")
}
println(for {
a <- someA
b <- None
_ = println("After none")
c <- someC
d <- someD
} yield a + b +c +d)
someA
None

The line “After none” did not get printed, neither did the print statements within someC and someD functions.

--

--