I'm trying to understand how for comprehension works by understanding the difference of the two below:
case class Item(name: String, value: Int)
def forCompWithVarAssignment() = {
val itemList = List(Item("apple", 10), Item("orange", -5), Item("coke", -2), Item("ensaymada", 20))
var someVar = 1
for {
item <- itemList
if someVar > 0
itemValue = item.value
if itemValue < 0
} {
println(s"got itemValue: $itemValue")
println(s"setting someVar to negative value.")
someVar = -1
}
}
def forCompWithOption() = {
val itemList = List(Item("apple", 10), Item("orange", -5), Item("coke", -2), Item("ensaymada", 20))
var someVar = 1
for {
item <- itemList
if someVar > 0
itemValue <- Option(item.value)
if itemValue < 0
} {
println(s"got itemValue: $itemValue")
println(s"setting someVar to negative value.")
someVar = -1
}
}
Now, the only difference of forCompWithVarAssignment() and forCompWithOption() are itemValue = item.value and itemValue <- Option(item.value) respectively.
Which, I believe, itemValue gets the same thing either way.
However, here's the tricky part.
The result of the forCompWithVarAssignment() is as follows:
got itemValue: -5
setting someVar to negative value.
got itemValue: -2
setting someVar to negative value.
While the result of forCompWithOption() is:
got itemValue: -5
setting someVar to negative value.
Question:
On forCompWithVarAssignment(), why did the loop still continued even if someVar is already -1 after it passes Item("orange", -5)?
I'm expecting that the loop will stop at Item("orange", -5) so got itemValue: -2 should have never been printed.