How to Slice List in Kotlin: Syntax and Examples
In Kotlin, you can slice a list using the
slice() function with a range or a list of indices. For example, myList.slice(1..3) returns a new list with elements from index 1 to 3.Syntax
The slice() function extracts elements from a list based on specified indices or ranges.
list.slice(indices: Iterable<Int>): Returns a new list with elements at the given indices.list.slice(range: IntRange): Returns a new list with elements in the specified index range.
Indices start at 0, and the original list is not modified.
kotlin
val myList = listOf("a", "b", "c", "d", "e") val sliceByRange = myList.slice(1..3) // elements at indices 1, 2, 3 val sliceByIndices = myList.slice(listOf(0, 2, 4)) // elements at indices 0, 2, 4
Example
This example shows how to slice a list using both a range and a list of indices. It prints the sliced lists to demonstrate the output.
kotlin
fun main() {
val fruits = listOf("Apple", "Banana", "Cherry", "Date", "Elderberry")
val sliceRange = fruits.slice(1..3) // Banana, Cherry, Date
val sliceIndices = fruits.slice(listOf(0, 2, 4)) // Apple, Cherry, Elderberry
println("Slice by range (1..3): $sliceRange")
println("Slice by indices (0, 2, 4): $sliceIndices")
}Output
Slice by range (1..3): [Banana, Cherry, Date]
Slice by indices (0, 2, 4): [Apple, Cherry, Elderberry]
Common Pitfalls
Common mistakes when slicing lists in Kotlin include:
- Using indices out of the list's bounds, which throws an
IndexOutOfBoundsException. - Confusing
slice()withsubList().slice()creates a new list, whilesubList()returns a view. - Using ranges that are empty or reversed, which results in an empty list.
kotlin
fun main() {
val numbers = listOf(10, 20, 30, 40, 50)
// Wrong: index 5 does not exist (list size is 5, max index 4)
// val wrongSlice = numbers.slice(2..5) // Throws exception
// Right: use valid range
val rightSlice = numbers.slice(2..4) // 30, 40, 50
println("Valid slice: $rightSlice")
}Output
Valid slice: [30, 40, 50]
Quick Reference
| Operation | Syntax | Description |
|---|---|---|
| Slice by range | list.slice(startIndex..endIndex) | Returns elements from startIndex to endIndex inclusive. |
| Slice by indices | list.slice(listOf(index1, index2)) | Returns elements at specified indices. |
| Sublist (view) | list.subList(startIndex, endIndex) | Returns a view from startIndex (inclusive) to endIndex (exclusive). |
| Index out of bounds | list.slice(invalidRange) | Throws IndexOutOfBoundsException if indices are invalid. |
Key Takeaways
Use
slice() with ranges or lists of indices to get parts of a list in Kotlin.Indices start at 0 and must be within the list size to avoid errors.
slice() returns a new list; it does not modify the original list.Avoid using invalid or reversed ranges to prevent empty results or exceptions.
For a view instead of a copy, consider
subList() with exclusive end index.