xcvd
xcvd

Reputation: 563

foreach in method to return value

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?

Upvotes: 3

Views: 10055

Answers (3)

Charlie 木匠
Charlie 木匠

Reputation: 2400

Don't Use Return in #Scala . The return keyword is not “optional” or “inferred”; it changes the meaning of your program, and you should never use it.

https://tpolecat.github.io/2014/05/09/return.html

Upvotes: 1

Christian
Christian

Reputation: 4593

It's because there is no else or a default return value.

If a method has return type Int, than all paths in that method must return an Int. This is not the case in your implementation. For example, if in the Array there would not be the number 3, nothing would be returned, which means the return type would be Unit.

Upvotes: 2

drexin
drexin

Reputation: 24403

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
}

Upvotes: 13

Related Questions