Library contents

Scala Queue.dequeueOption

An immutable queue returns None when no patient is available to dequeue.

A simple example

Queue.dequeueOption

  1. Start with Queue containing no items
  2. Do this Request the first item
  3. Result No item available
Check for an empty result or handle the empty-queue failure before using a value.

Syntax

Scala syntax
patients.dequeueOption
Run these examples in Scala

Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.

scalac Lesson.scala
scala Lesson

Call the next person at the clinic

A receptionist calls patients from the morning queue. If the final patient has already checked in, the screen should display an empty-queue message instead of trying to issue another number.

ResultNo patients waiting
Lesson.scala
import scala.collection.immutable.Queue

object Lesson {
    def main(args: Array[String]): Unit = {
        val patients = Queue.empty[String]
        patients.dequeueOption match {
            case Some((patient, _)) => println(patient)
            case None => println("No patients waiting")
        }
    }
}
Output
No patients waiting

The queue has no patient at its front. The screen reports the empty state to the receptionist.

Advertisements

Call a waiting pupil

The music desk has one pupil in its equipment queue. Take the next name from the queue. An empty queue should send the desk back to waiting.

GivenQueue [Mila]
Worked resultVisitor ready

Check an empty ticket queue

The counter opens before anyone has taken a ticket. Take the next name from the queue. An empty queue should send the desk back to waiting.

GivenQueue []
Worked resultWait for next visitor

What to watch for

The successful result contains the patient and the new queue. Keep the new queue to consume the ticket.

Documentation for Queue.dequeueOption