打破每个闭包与从方法返回

时间:2016-05-06 03:04:07

标签: groovy

以下方法中的第一个return不会结束该方法,而是会突破循环

boolean isAnyColorRed() {
  colors.each { 
    if (it.type == "red")
       return true // does not end the method but instead breaks the loop.
  }
  return false
}

什么是变通方法?此?

boolean isAnyColorRed() {
  boolean foundRed = false
  colors.each { 
    if (it.type == "red") {
        foundRed = true
        return //break the loop
    } 
  }
  if (foundRed)
    return true
  else
    return false
}

1 个答案:

答案 0 :(得分:0)

这是一种更加时髦的方式:

colors.any { it.type == 'red' }

这将返回truefalse,因此您可以在if表达式中使用它...

相关问题