Scala alternative to an infinite loop

Viewed 1552

Is there any more functional alternative in Scala for an infinite loop?

while(true) {
  if (condition) {
    // Do something
  } else {
    Thread.sleep(interval);
  }
}
4 Answers

Just to add to Stefano's great answer, in case someone is looking to a use-case like mine:

I was working on tasks from Kafka Streams course and needed to create an infinite stream of mock events to Kafka with some fields being completely random(amounts), but others rotated within a specific list(names).

The same approach with continually can be used passing a method(via ETA expansion) to it and traversing the bounded variable afterwards:

  for {record <- continually(newRandomTransaction _)
       name <- List("John", "Stephane", "Alice")} {
    producer.send(record(name))
  }

where the signature of newRandomTransaction is as follows:

  def newRandomTransaction(name: String): ProducerRecord[String, String] = {
   ...
  }
Related