1

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?

mck
  • 40,932
  • 13
  • 35
  • 50
  • 3
    `return` causes the function to stop at that point and returns 1 because it's the first iteration in the `foldLeft` operation. The second sumR is not computed. – mck Apr 12 '21 at 10:28
  • 1
    Have a look https://users.scala-lang.org/t/dont-use-return-in-scala/3688/11 – mfirry Apr 12 '21 at 10:31
  • @mck is it about the fact that `return` is syntatically in `foo`? To my eye, `return` should return from `sumR` function. After all, we have two calls of `sumR` so there should be two returns as well. – IntrestedInSpark Apr 12 '21 at 10:33
  • Yes, `return` pertains to `foo`. A lambda function cannot have a `return`. – mck Apr 12 '21 at 10:34
  • Why? Because of lambda is expression? – IntrestedInSpark Apr 12 '21 at 10:35
  • See [this question](https://stackoverflow.com/questions/17754976/scala-return-statements-in-anonymous-functions) . – mck Apr 12 '21 at 10:38
  • 1
    Never ever use `return` in **Scala**, or is not needed and can cause bugs like this one: https://tpolecat.github.io/2014/05/09/return.html – Luis Miguel Mejía Suárez Apr 12 '21 at 12:38

1 Answers1

5

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
mck
  • 40,932
  • 13
  • 35
  • 50
  • Thanks, very good answer. Anyway, it looks like `lambda` function is semantically differant than `def` function – IntrestedInSpark Apr 12 '21 at 10:36
  • Just in case someone want more information about the difference between **function** and *method**; it is a FAQ: https://docs.scala-lang.org/tutorials/FAQ/index.html#whats-the-difference-between-methods-and-functions – Luis Miguel Mejía Suárez Apr 12 '21 at 13:02