Reputation: 115
let's consider:
def foo: Int = {
val sumR: List[Int] => Int = _.foldLeft(0)((n, m) => return n + m)
sumR(List(1,2,3)) + sumR(List(4,5,6))
}
scala> foo
res4: Int = 1
Why first part of sumR(List(1,2,3)) + sumR(List(4,5,6))
expression is treated better? After all, return
should lead to returning from sumR
. So, why the result is not equal to 1+4
?
Upvotes: 1
Views: 65
Reputation: 42342
The return
is related to the foo
method rather than the sumR
function, so return
causes the foo
method to stop at that point and returns 1 because it's the first iteration in the foldLeft
operation. The second sumR
is not computed.
If you want 5 as the result, you should define sumR
as a method rather than an anonymous function, so that return
causes the sumR
method to stop, rather than the foo
method to stop.
def foo: Int = {
def sumR(l: List[Int]): Int = l.foldLeft(0)((n, m) => return n + m)
sumR(List(1,2,3)) + sumR(List(4,5,6))
}
foo
// Int = 5
Upvotes: 5