Kotlin .slice()
Published Dec 2, 2024
Contribute to Docs
In Kotlin, the .slice() function is used to create a new list containing elements from the specified range or indices of an array.
Syntax
array.slice(indices: IntRange): List<T>
Or, alternatively:
array.slice(indices: List<Int>): List<T>
indices: IntRange: A range of indices from which the elements will be selected.indices: List<Int>: A list of specific indices representing the elements to be included in the new list.
Example
The following example demonstrates the usage of the .slice() function with both IntRange and List<Int>:
fun main() {val array = arrayOf(10, 20, 30, 40, 50)// Using IntRange to slice the arrayval sliceRange = array.slice(1..3) // Includes elements at indices 1, 2, and 3println("Slice using IntRange: $sliceRange")// Using List<Int> to slice the arrayval sliceList = array.slice(listOf(0, 2, 4)) // Selects elements at indices 0, 2, and 4println("Slice using List<Int>: $sliceList")}
The above code produces the following output:
Slice using IntRange: [20, 30, 40]Slice using List<Int>: [10, 30, 50]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Kotlin on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn Kotlin, the expressive, open-source programming language developed by JetBrains.
- Beginner Friendly.9 hours