foreach in method to return value

foreach, methods, scala

Solution

That is because your lambda in the `foreach` does guarantee to return a value. If you provide a default return value it should work.

def a: Int = {
  for(i <- Array(1,2,3,4,5)){
    if(i == 3)
      return i
  }
  0
}

Problem

``` def a: Int = { for(i <- Array(1,2,3,4,5)){ if(i == 3) return i } } ``` The above method will not compile, I get the following error: ``` error: type mismatch; found : Unit required: Int for(i <- Array(1,2,3,4,5)){ ^ ``` The expected behaviour is that the method returns 3. What is wrong with my code?

Original source