Kotlin Map.containsKey
Check whether a parcel is registered even if a driver has yet to be assigned.
A simple example
Map.containsKey
- Start with A = 2
- Do this Look for key A
- Result Present
Syntax
drivers.containsKey(parcel)
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 parcel whose driver is still unassigned
A dispatch desk registers parcels before assigning drivers. Parcel P7 already has a record with an empty assignment, and the operator must distinguish it from a parcel that has never been registered.
fun main() {
val drivers = mapOf<String, String?>("P7" to null)
if (drivers.containsKey("P7")) println("Registered")
}
Registered
P7 appears in the register and the driver field is still unassigned.
Find an unassigned booking
A clinic already has booking B12, although a clinician has yet to be assigned. The desk checks whether the identifier has a record before creating one. Is the key already present?
Look for a second ticket
A counter has recorded ticket T2 and receives a query for T3. The desk checks whether the identifier has a record before creating one. Is the key already present?
What to watch for
A nullable driver can belong to an existing key. Checking the looked-up value for null loses that distinction.