foreach in method to return value

霸气de小男生 提交于 2020-01-04 15:31:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!