Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

only once in while loop with scala

I'm beginning with Scala. I have a program which have a method with a while loop which run until the program is not ended.

But for my test, I need to execute this method only once (or twice). In java, I would have used a mutable variable that I would have decremented in order to stop my treatment.

Maybe a condition inside my while loop that I override for my test.

def receive = {
    val iterator = stream.iterator()
    while (iterator.hasNext && my_condition()) {
        something_to_do
    }
}

I know it's a stupid question, but could you please advice me ?

like image 303
Guillaume Avatar asked May 31 '26 12:05

Guillaume


1 Answers

Try:

iterator.takeWhile(my_condition).foreach(something_to_do)

or:

iterator.take(n).foreach(something_to_do)

if you just want the first n entries.

Or, if something_to_do returns a result (rather than Unit), and you want to return an iterator of those results, you can use:

iterator.takeWhile(my_condition).map(something_to_do)

(or .take(n).map(...) )

like image 146
Shadowlands Avatar answered Jun 04 '26 01:06

Shadowlands



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!