Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional code for looping with early exit

How can I refactor this code in functional style (scala idiomatic)

def findFirst[T](objects: List[T]):T = {
  for (obj <- objects) {
    if (expensiveFunc(obj) != null) return obj
  }
  null.asInstanceOf[T]
}
like image 824
snappy Avatar asked Jul 18 '11 07:07

snappy


1 Answers

This is almost exactly what the find method does, except that it returns an Option. So if you want this exact behavior, you can add a call to Option.orNull, like this:

objects.find(expensiveFunc).orNull
like image 155
sepp2k Avatar answered Oct 06 '22 02:10

sepp2k