Scala return value from loop a

I have the following code snippet

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 conditionoccurs for a number from 1 to 10, return the number, otherwise return an invalid result (-1).

It works great, but it violates some of the principles of functional programming due to returnin a loop for. How can I reorganize this method (I also received unit tests) and delete the return statements. I suppose I should use yield, but it seems to be creating a list, I just need one value.

+5
source share
2 answers

This is a functional translation of your code:

def my_function(condition: Int => Boolean): Int = {
  (0 to 10).find(i => condition(i)).getOrElse(-1)
}

Or more succinctly:

def my_function(condition: Int => Boolean): Int = {
  (0 to 10).find(condition).getOrElse(-1)
}

find, , . find , . Option, , None. getOrElse Option , , -1, .

" ", , -1 Scala. . Option[Int], None , . :

def my_function(condition: Int => Boolean): Option[Int] = {
  (0 to 10).find(condition)
}

println(my_function(_ > 5))   // Some(6)
println(my_function(_ > 11))  // None
+13

def my_function(condition: Int => Boolean): Int =
  (1 to 10).find(condition).getOrElse(-1)

scala " ", return

def my_function(condition: Int => Boolean) : Option[Int] =
  (1 to 10).find(condition)

for-yield

def my_function(condition: Int => Boolean): Int =
  (for (i <- 1 to 10; if condition(i)) yield i).headOption.getOrElse(-1)

def my_function(condition: Int => Boolean): Int =
  (for (i <- 1 to 10; if condition(i)) yield i).headOption

@Jan

+5

All Articles