3

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 ?

Guillaume
  • 694
  • 1
  • 6
  • 15
  • 2
    There are multiple approaches to this problem. It's been asked before: http://stackoverflow.com/questions/2742719/how-do-i-break-out-of-a-loop-in-scala?rq=1 – jwvh Aug 22 '15 at 17:02

3 Answers3

3

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

Shadowlands
  • 14,994
  • 4
  • 45
  • 43
2

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.

elm
  • 20,117
  • 14
  • 67
  • 113
0

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)
mattinbits
  • 10,370
  • 1
  • 26
  • 35