Kotlin List.toList
Capture the current guest list before accepting late additions.
A simple example
List.toList
- Start with Original list A, B
- Do this Copy it, then append C to the original
- Result Copy still has A, B
Syntax
printed = draft.toList()
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.jarFreeze the guest list used to print badges
A school prints badges from a draft guest list. A late guest joins after printing starts, so the team keeps a snapshot that records exactly how many badges belonged to the original run.
fun main() {
val draft = mutableListOf("Mira", "Sam")
val printed = draft.toList()
draft.add("Nia")
println(printed.size)
}
2
The count for the original badge run remains two.
Freeze the morning guest list
The school prints the first two names before a late guest registers. After saving a snapshot, add the late entry only to the working list. Which names remain visible on the snapshot?
Save a stage checklist
A technician archives the checklist before adding a new microphone. After saving a snapshot, add the late entry only to the working list. Which names remain visible on the snapshot?
What to watch for
The result exposes a read-only interface. Mutable elements still need their own copy for a deep snapshot.