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?
That is because your lambda in the
foreachdoes guarantee to return a value. If you provide a default return value it should work.