Kotlin getOrNull
Handle a saved seat position outside the current list before printing a new ticket.
A simple example
getOrNull
- Start with A list containing only A
- Do this Ask for the third item
- Result Outside the list
Syntax
seats.getOrNull(index)
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.jarFind a seat after the coach changes
A bus operator replaces a coach with a smaller one. A passenger's saved seat position now falls outside the new seating list, so the booking screen must ask them to choose again.
fun main() {
val seats = listOf("Window", "Aisle")
println(seats.getOrNull(2) ?: "Choose another seat")
}
Choose another seat
The saved position is just beyond the two-seat list. The booking desk asks for a replacement seat.
Open the last appointment
A desk offers two appointments and a visitor selects index one. Look up the zero-based slot. Ask the user to choose again if that position falls outside the available list.
Reject a stale bus selection
An old menu points to index two after the coach list shrinks to two stops. Look up the zero-based slot. Ask the user to choose again if that position falls outside the available list.
What to watch for
The saved index is zero-based. A list of two seats ends at position one.