scala避免返回,同时仍然在执行迭代

use*_*956 2 scala

当我写下以下内容时,IntelliJ的scalastyle对我很不满.它不喜欢我写的回报.

def hasAnnotation(symbol: Symbol, annotation: Type): Boolean = {
  for (a <- symbol.annotations) {
    if ( a.tpe =:= annotation ) return true  // AVOID USING RETURN!!!
  }
  false
}
Run Code Online (Sandbox Code Playgroud)

为什么要添加回归邪恶?

如何在不返回的情况下快速迭代?

nat*_*bbs 11

做你要求的更实用的方法是

def hasAnnotation(symbol: Symbol, annotation: Type) = 
   symbol.annotations.exists(_.type =:= annotation)
Run Code Online (Sandbox Code Playgroud)

这将在找到满足谓词的第一项时发生短路.回归并不邪恶,只是更加迫切.这是另一篇关于退出循环的帖子的链接