Saturday, July 20, 2013

Scala break out for / while loops...

Ok, first of all I have to give credit to the following post since it help me to come out with a solution.

http://stackoverflow.com/questions/2742719/how-do-i-break-out-of-a-loop-in-scala

Let say that in java you have something like this:

public boolean validateObject(Answer anObject) {...}

And inside of another method you have a loop that you want to break when validateObject method returns "true". In Java it would looks like:

public void aLoopMethod() {
   boolean temp = false;
   List[Answer] list = methodGetAnswers();
   int index = 0;
   while (temp == false || index < list.size() ) {
      temp = validateObject(list.get(index));
      index++;
   }
}

Translated to Scala it would be something like this:

val temp = false
(0 to list.size).toStream.takeWhile(_ => !temp).foreach(i => (temp = validateObject(uuid,list.get(i))))

Seems to be easy, but it took some hours to figure out the solution. I hope it helps you...




No comments:

Post a Comment