Guillaume
Guillaume

Reputation: 694

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 ?

Upvotes: 3

Views: 872

Answers (3)

Shadowlands
Shadowlands

Reputation: 15074

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(...) )

Upvotes: 3

elm
elm

Reputation: 20435

Consider this for comprehension,

for (_ <- iterator if my_condition()) something_to_do

where each iterated value is ignored (note _) and the todo part is invoked while the condition holds.

Upvotes: 2

mattinbits
mattinbits

Reputation: 10428

I think an approach like the following is acceptable:

import akka.actor.{Props, Actor}

import scala.io.Source

object TestableActor {

  def props = Props(new TestableActor())

  def testProps = Props(new TestableActor(true))

  case class Message(stream: Stream)
}

class TestableActor(doOnce: Boolean = false) extends Actor {

  import TestableActor._

  val stream: Stream = ???

  def receive = {
    case Message(stream) =>
      val iterator = stream.iterator
      if(doOnce) {
        something_to_do
      } else {
        while (iterator.hasNext && my_condition()) {
          something_to_do
        }
      }
  }

  def my_condition(): Boolean = ???

  def something_to_do: Unit = ???
}

In your production code, use

context.actorOf(TestableActor.props)

In your test use

TestActorRef[TestableActor](TestableActor.testProps)

Upvotes: 0

Related Questions