Here's how the Scala 2.11.8 standard library does it.
From LinearSeqOptimized.scala:
override /*IterableLike*/
def exists(p: A => Boolean): Boolean = {
var these = this // <--- Look, a var!
while (!these.isEmpty) {
if (p(these.head)) return true // <--- Look, a return!
these = these.tail
}
false
}
In other words, Scala uses a while
loop, which mutates a var that points to the next object, and breaks out of the loop when it reaches the desired object.
I found out, when comparing answers to a similar question, that while
with some sort of mutating iteration variable is the most efficient way to write this in Scala. Pure-functional approaches like recursion, Streams, etc. are slower—as much as 8 times slower (and still without scanning beyond the first 'true' element). I gather that the best approach is to use some kind of mutable iterator when you need to do a linear search and hide it inside a function that presents a pure-functional interface to the rest of the program. The Scala standard library does that in many places for you, so you get the best possible performance with a pure-functional interface.