Lesson contents

Scala — Post-test loops in Scala 2 and Scala 3

Scala 2.13 supports do-while. Scala 3 dropped that syntax, so a while condition block that performs the first operation before testing is a portable alternative.

A simple example

Print first, then test

  1. Start with n starts at 1
  2. Do this Print n, add 1
  3. Result Stop at 4
The first print happens before the stopping test. The loop prints 1, 2 and 3 on separate lines.
Lesson.scala
object Lesson extends App {
    var n = 1
    do {
        println(n)
        n += 1
    } while (n <= 3)
}
Output
1
2
3
Advertisements

Poll until ready or the attempt limit

Count the first poll for every request, even if it is already ready. Stop after success or after the configured maximum number of attempts. Run the comparison in Scala 2.13. pollCount2 shows the native do-while form. In pollCountPortable the condition block increments the counter and yields the Boolean used by while. Only the portable function is needed in Scala 3.

First check: Busy. Second check: Ready. Checks made: 2.
Check a printer until it is ready

A print desk checks the printer once before deciding whether to check again. If the printer answers ready on the second check, the loop stops there. A limit of three checks keeps an offline printer from holding up the desk.

Run the example

Use Scala 2.13. Run these commands from the directory containing the example.

scalac Lesson.scala
scala Lesson
Lesson.scala
object Lesson {
  def pollCount2(readyOn: Int, limit: Int): Int = {
    var attempts = 0
    do {
      attempts += 1
    } while (attempts < readyOn && attempts < limit)
    attempts
  }

  def pollCountPortable(readyOn: Int, limit: Int): Int = {
    var attempts = 0
    while ({
      attempts += 1
      attempts < readyOn && attempts < limit
    }) ()
    attempts
  }

  def main(args: Array[String]): Unit = {
    for ((readyOn, limit) <- List((5, 1), (2, 3), (8, 3))) {
      val attempts = pollCount2(readyOn, limit)
      assert(attempts == pollCountPortable(readyOn, limit))
      println(attempts)
    }
  }
}
Output
1
2
3

With one permitted attempt, the first case stops at 1. The second becomes ready on attempt 2. The last case never reaches readiness within its three-attempt limit.

Apply the loop to a retry queue

Simulate a job using prerecorded replies. T means a temporary failure, S means success, and X means permanent rejection. Process at most two replies per job. Stop on S or X and report how many replies were consumed.

First reply: Temporary failure. Next reply: Success. Attempts used: 2.
Handle a temporary print failure

A queue can retry a temporary failure once under a two-attempt limit. A temporary failure followed by success finishes the job. A permanent rejection stops the job immediately and leaves the next reply unused.

Run this example

Save this program as Lesson.scala and run it separately.

scalac Lesson.scala
scala Lesson
Lesson.scala
object Lesson {
  case class Result(outcome: String, attempts: Int)

  def process(responses: String, limit: Int): Result = {
    val replies = responses.iterator.take(limit)
    var used = 0
    while (replies.hasNext) {
      val response = replies.next()
      used += 1
      response match {
        case 'S' => return Result("sent", used)
        case 'X' => return Result("rejected", used)
        case _   => ()
      }
    }
    Result(if (used == limit) "limit reached" else "no response", used)
  }

  def main(args: Array[String]): Unit = {
    val jobs = List("A" -> "TS", "B" -> "XS", "C" -> "TTS", "D" -> "")
    for ((id, responses) <- jobs) {
      val Result(outcome, attempts) = process(responses, 2)
      println(s"$id: $outcome ($attempts)")
    }
  }
}
Output
A: sent (2)
B: rejected (1)
C: limit reached (2)
D: no response (0)

Job A succeeds on its second reply. B stops at the rejection before its later success. C reaches the attempt limit with a success still unread. D has no recorded reply, so its count stays zero. Try raising the limit to three: only C changes, succeeding on the third reply.

Try it yourself

A request is ready on the first poll and allows three attempts. How many polls run?

Check your answer

Exactly one. The success check happens after the first poll. The example assumes a positive attempt limit.

Scala language specification

Related tags

  • Scala
  • post-test loops
  • retries
  • termination