In Scala the preferred way is to use methods of the Standard Library and no clearly supported, good way to break out of functions.
An option to achieve the result wished is to use takeWhile
. If some side effecting logic is wished that can be applied by using foreach
. An additional check can for example be introduce by introducing a predicate
.
The given example code could be improved by using the predicate in a filter, but I think one gets the basic idea.
Define the functions
def someFunction(x: Int): Unit = if ( predicate(x)) println(x)
def predicate : (Int) => Boolean = _ % 2 == 0
(0 to 5).takeWhile(_ != 3) foreach someFunction
Example
(0 to 5).takeWhile(_ != 3) foreach someFunction
0
2
someFunction: (x: Int)Unit
predicate: Int => Boolean