我在 Scala 库的 List.scala 中看到了以下实现:
override final def forall(p: A => Boolean): Boolean = {
var these: List[A] = this
while (!these.isEmpty) {
if (!p(these.head)) return false
these = these.tail
}
true
}
该方法可以递归实现以摆脱 var 和 while 循环。通过在线阅读所有可用的书籍、博客、文章等,我的印象是我们应该在 Scala 中尽可能多地遵循递归方法。