Reputation: 563
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
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
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
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