Kotlin List.slice
Read the middle batch of an order queue using a range.
A simple example
List.slice
- Start with A, B, C
- Do this Select the first two items
- Result A, B
Syntax
orders.slice(indices)
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.jarSelect two orders for the packing bench
A packing bench takes a small batch from the middle of the day's queue. The supervisor wants orders B and C on this bench while the other orders stay visible in the full queue.
From the programval orders = listOf("A", "B", "C", "D")
ResultB, C
fun main() {
val orders = listOf("A", "B", "C", "D")
println(orders.slice(1 until 3).joinToString(", "))
}
B, C
The requested range contains only orders B and C.
Advertisements
Prepare the next workshop roster
A teacher reads a workshop roster in arrival order. The coordinator prints the first two entries on a separate slip. Which entries appear, in order?
GivenMira · Ivo · Bea
Worked resultMira · Ivo
Work from the delivery round
A courier has three labelled stops in route order. The coordinator prints the first two entries on a separate slip. Which entries appear, in order?
GivenPark · Mill · Pier
Worked resultPark · Mill
What to watch for
Use until for an exclusive upper bound. The .. operator includes both endpoints.