Kotlin List.getOrNull
Read one name from an ordered roster after checking its length.
A simple example
List.getOrNull
- Start with A, B, C
- Do this Read the second element
- Result B
Syntax
names.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.jarRead the second name on the pickup roster
A teacher calls children in their recorded pickup order. The office asks for the second name on the roster, so the teacher checks that the list contains at least two entries before reading it.
From the programval names = listOf("Asha", "Mira", "Sam")
ResultMira
fun main() {
val names = listOf("Asha", "Mira", "Sam")
names.getOrNull(1)?.let { println(it) }
}
Mira
Mira occupies the second position on the three-person roster.
Advertisements
Prepare the next workshop roster
A teacher reads a workshop roster in arrival order. Who or what occupies the second position? Count from the front of the list.
GivenMira · Ivo · Bea
Worked resultIvo
Work from the delivery round
A courier has three labelled stops in route order. Who or what occupies the second position? Count from the front of the list.
GivenPark · Mill · Pier
Worked resultMill
What to watch for
getOrNull returns null for an unavailable position. A nullable element can also yield null.