To slice a list in Kotlin, you can use the subList
method, which allows you to create a view of the list between the specified start and end indices.
In this example,
numbers
with integer values.subList
method on the list object numbers
to create a new list from index 1 to index 3 (exclusive).subList
method returns a view of the specified range within the original list.fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
val slicedNumbers = numbers.subList(1, 4)
println("Sliced list: $slicedNumbers")
}
Sliced list: [2, 3, 4]
In this example,
words
with string values.subList
method on the list object words
to create a new list from index 2 to index 5 (exclusive).subList
method returns a view of the specified range within the original list.fun main() {
val words = listOf("apple", "banana", "cherry", "date", "elderberry")
val slicedWords = words.subList(2, 5)
println("Sliced list: $slicedWords")
}
Sliced list: [cherry, date, elderberry]
In this tutorial, we learned How to Slice a List in Kotlin language with well detailed examples.