The slice function takes a list or range as an argument and returns a list of elements at specified list indexes.
Take a look at the following example:
var numbers = listOf<Int>(1,2,3,4,5,6,7,8,9,10)
var newList = numbers.slice(0..4)
println("Slice of first four elements")
println(newList)
newList = numbers.slice(listOf(1,4,8))
println("Slice of selected elements")
println(newList)
The numbers.slice(0..4) function takes a range from zero to four and returns a list of elements from index 0 to index 4 from the numbers list.
The numbers.slice(listOf(1,4,8)) slice function can pick elements from different locations. In this example, the slice function picks elements 2, 5, and 9 from indexes 1, 4, and 8. Verify the output of the slice function by providing different values:
[1, 2, 3, 4, 5]
[2, 5, 9]