问题
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?
回答1:
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
}
回答2:
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.
回答3:
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
来源:https://stackoverflow.com/questions/10043095/foreach-in-method-to-return-value