foreach方法返回值 [英] foreach in method to return value

查看:1844
本文介绍了foreach方法返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)){
             ^

预期的行为是该方法返回3.我的代码有什么问题?

The expected behaviour is that the method returns 3. What is wrong with my code?

推荐答案

这是因为您在foreach中的lambda确实保证会返回一个值.如果您提供默认的返回值,则应该可以使用.

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
}

这篇关于foreach方法返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆