- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
Kotlin Array - sliceArray() Function
The Kotlin array sliceArray() function is used to return a new array containing subset of element in the specified indices range. This function only slices an array not collection (list, hashSet).
The indices contain two parameters: startIndex, and endIndex.
Syntax
Following is the syntax of Kotlin array sliceArray() function −
fun <T> Array<T>.sliceArray( indices: Collection<Int> ): Array<T>
Parameters
This function accepts indices as a parameters represents startIndex and endIndex.
Return value
This function returns an array containing elements of this array at specified index range.
Example 1
The following is a basic example to demonstrate the use of sliceArray() function −
fun main(args: Array<String>){
var arr = arrayOf<Int>(2, 4, 5, 6, 1).sliceArray(1 .. 3)
println("The array after slice: ")
// printing the slice array
for (i in 0 until arr.size){
println(arr.get(i))
}
}
Output
The above code generate following output −
The array after slice: 4 5 6
Example 2
Now, Let's see another example. Here, we create an array of string. We then use sliceArray() function to slice array's element in the specified indices range −
fun main(args: Array<String>){
var elements = arrayOf<String>("tutorialspoint", "Hyderabad", "India", "tutorix").sliceArray(1..3)
// printing the slice array
println(elements.joinToString(prefix = "[", postfix="]"))
}
Output
Following is the output −
[Hyderabad, India, tutorix]
Example 3
The below example uses sliceArray() function to return an array containing weekdays −
fun main(args: Array<String>) {
val daysOfWeek = arrayOf("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
// Slice the array to get the weekdays
val weekdays = daysOfWeek.sliceArray(1..5)
println(weekdays.joinToString(prefix = "[", postfix = "]"))
}
Output
Following is the output −
[Monday, Tuesday, Wednesday, Thursday, Friday]