Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
scala在简化迭代的同时避免返回_Scala - Fatal编程技术网

scala在简化迭代的同时避免返回

scala在简化迭代的同时避免返回,scala,Scala,IntelliJ的scalastyle在我写以下内容时对我非常生气。我写了一封回信,可不是这样的 def hasAnnotation(symbol: Symbol, annotation: Type): Boolean = { for (a <- symbol.annotations) { if ( a.tpe =:= annotation ) return true // AVOID USING RETURN!!! } false } def hasaAnnota

IntelliJ的scalastyle在我写以下内容时对我非常生气。我写了一封回信,可不是这样的

def hasAnnotation(symbol: Symbol, annotation: Type): Boolean = {
  for (a <- symbol.annotations) {
    if ( a.tpe =:= annotation ) return true  // AVOID USING RETURN!!!
  }
  false
}
def hasaAnnotation(符号:符号,注释:类型):布尔={

对于(a来说,一种更实用的方法是

def hasAnnotation(symbol: Symbol, annotation: Type) = 
   symbol.annotations.exists(_.type =:= annotation)

找到第一个满足谓词的项时,这将短路。返回不是邪恶的,它只是更重要。指向另一篇文章的链接谈到从循环返回,nattyddubbs有一个很好的函数实现,没有返回,但我可以补充一点intellij为什么要警告您

基本上,
return
在scala中的工作原理与您可能期望的略有不同-jetbrains的员工知道这一点,并添加了一个警告,以确保您真正想要返回

问题是它会将调用者返回到出现返回的方法,而不是函数。最好在匿名函数中看到这一点,例如,假设您有一个函数对列表求和

scala> def summer(as: List[Int]): Int = as.foldRight(0)((i,j) => i + j)

scala> summer(List(33, 42, 99))
res2: Int = 174
酷。如果你用return怎么办

scala> def summer(as: List[Int]): Int = as.foldRight(0)((i,j) => return i + j)

scala> summer(List(33, 42, 99))
res3: Int = 99
函数的含义已经完全改变了…您可能没有预料到

好的,您可能永远不会在这样一个简单的函数中编写返回,但是您可以在更复杂的lambda中轻松地编写返回,并最终得到您不期望的结果


Rob Norris写了一篇关于scala回归的博文,这篇博文非常值得一读

如果答案能澄清为什么
易碎
被认为是邪恶的,那就太好了。关于这里的一些讨论是的,如下链接,但对我简单的头脑来说并不是很清楚。链接的博文是易碎的,没有给出不同意见。链接的答案使breakable成为一个子选项。它应该是“受stdlib的祝福”或者被证明是有害的。