Kotlin ArrayDeque.removeFirstOrNull
An empty deque can return null as the ordinary outcome of a request for the next ticket.
A simple example
ArrayDeque.removeFirstOrNull
- Start with Queue containing no items
- Do this Request the first item
- Result No item available
Syntax
patients.removeFirstOrNull()
Run these examples in Kotlin
Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jarCall 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.
fun main() {
val patients = ArrayDeque<Int>()
println(patients.removeFirstOrNull()?.toString() ?: "No patients waiting")
}
No patients waiting
The queue has no patient at its front. The screen reports the empty state to the receptionist.
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.
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.
What to watch for
Store non-null ticket numbers when null represents an empty waiting room.