Kotlin List slice()
Syntax & Examples
Syntax of List.slice()
There are 2 variations for the syntax of List.slice() extension function. They are:
1.
fun <T> List<T>.slice(indices: IntRange): List<T>
This extension function returns a list containing elements at indices in the specified indices range.
2.
fun <T> List<T>.slice(indices: Iterable<Int>): List<T>
This extension function returns a list containing elements at specified indices.
✐ Examples
1 Example
In this example,
- We create a list of characters named
list
containing elements'a', 'b', 'c', 'd', 'e'
. - We use the
slice()
function with the range1..3
to get elements at indices1, 2, 3
. - The result, which is a list containing elements
'b', 'c', 'd'
, is stored inresult
. - We print
result
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c', 'd', 'e')
val result = list.slice(1..3)
println(result)
}
Output
[b, c, d]
2 Example
In this example,
- We create a list of integers named
list
containing elements10, 20, 30, 40, 50
. - We create a list of indices named
indices
containing elements1, 3, 4
. - We use the
slice()
function with the indices list to get elements at indices1, 3, 4
. - The result, which is a list containing elements
20, 40, 50
, is stored inresult
. - We print
result
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(10, 20, 30, 40, 50)
val indices = listOf(1, 3, 4)
val result = list.slice(indices)
println(result)
}
Output
[20, 40, 50]
3 Example
In this example,
- We create a list of strings named
list
containing elements"apple", "banana", "cherry", "date", "elderberry"
. - We use the
slice()
function with the range2 until 5
to get elements at indices2, 3, 4
. - The result, which is a list containing elements
"cherry", "date", "elderberry"
, is stored inresult
. - We print
result
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry")
val result = list.slice(2 until 5)
println(result)
}
Output
[cherry, date, elderberry]
Summary
In this Kotlin tutorial, we learned about slice() extension function of List: the syntax and few working examples with output and detailed explanation for each example.