-3

I want to create something like below in scala.

I am writing it in c, but i want to do exactly same in scala.

int bool = 0,i,j;
for(j=0;j<5;j++){
    for(i=0;i<5;i++){
        if(i==3)
           bool=1;
           break;
    }
    if(bool==0)
        continue;
    some function....
}
Mahek Shah
  • 485
  • 2
  • 5
  • 17

1 Answers1

3

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
Andreas Neumann
  • 10,734
  • 1
  • 32
  • 52