I have the following piece of code
def my_function(condition: Int=>Boolean): Int = {
for (i <- 0 to 10)
if (condition(i)) return i
return -1
}
The code is simple: if some condition is met for a number between 1 and 10, return the number, else return invalid result (-1).
It works perfectly fine, but it violates some of the functional programming principles, because of the return in the for cycle. How can I refactor this method (I got unit tests, too) and remove the return statements. I suppose that I must use yield, but it seems to produce list, I just need one value.
This is the functional translation of your code:
Or more succinctly as:
I’ve used the
findmethod which takes, as an argument, a function that produces a Boolean. Thefindmethod returns the first item in the collection that satisfies the condition. It returns the item as anOptionso that if there is no satisfying item, then the result will beNone. ThegetOrElsemethod ofOptionwill return the found result if there is one, and return-1if there isn’t.However, you should not use “error codes” like returning -1 in Scala programming. They are bad practice. Instead your should throw an exception or return an
Option[Int]such that returningNoneindicates no value was found. The right way to do this would be something like: