snappy
snappy

Reputation: 2781

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]
}

Upvotes: 17

Views: 2141

Answers (3)

user unknown
user unknown

Reputation: 36229

How about a fold?

Our somehow pseudo-expensive function:

scala> def divByFive (n: Int) : Option[Int] = {
     | println ("processing " + n)               
     | if (n % 5 == 0) Some (n) else None } 
divByFive: (n: Int)Option[Int]   

Folding on an Option:

scala> ((None: Option[Int]) /: (1 to 11)) ((a, b) => 
     |   if (a != None) a else divByFive (b)) 
processing 1
processing 2
processing 3
processing 4
processing 5
res69: Option[Int] = Some(5)

Upvotes: 0

paradigmatic
paradigmatic

Reputation: 40461

First, don't use null in Scala (except when interacting with Java code) but Options. Second, replace loops with recursion. Third, have a look at the rich API of Scala functions, the method you are looking for already exists as pointed by sepp2k.

For learning puprose your example could be rewritten as:

def findFirst[T](objects: List[T]):Option[T] = objects match {
    case first :: rest if expensiveFunc( first ) != null => Some( first )
    case _ :: rest => findFirst( rest )
    case Nil  => None
}

Upvotes: 6

sepp2k
sepp2k

Reputation: 370102

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

Upvotes: 22

Related Questions