Kotlin Array - slice() Function



The Kotlin array slice() function is used to create a list containing elements of an array at indices in the specified indices range.

The indices contain two parameters: startIndex, and endIndex both are optional parameters, By default, startIndex is 0, and endIndex is the length of this array.

Syntax

Following is the syntax of Kotlin array slice() function −

fun <T> Array<out T>.slice(indices: IntRange): List<T>

Parameters

This function accepts indices as a parameters represents startIndex and endIndex.

Return value

This function returns a list containing elements from startIndex to endIndex.

Example 1

The following is a basic example to demonstrate the use of slice() function −

fun main(args: Array<String>) {
   val numbers = arrayOf<String>("one", "two", "three", "four", "five", "six")
   //slice the element from index 1 to 3
   println("List after slice: " + numbers.slice(1..3))
}

Output

The above code generate following output −

List after slice: [two, three, four]

Example 2

Now, Let's see another example. Here, we create an array of Integer. We then use slice() function to slice array's element with increment by 2 steps −

fun main(args: Array<String>) {
   val numbers = arrayOf<Int>(1, 2, 3, 4, 5, 6)
   // slice the element from 0 to 4 with step by 2
   println("List after slice: " + numbers.slice(1..4 step 2))
}

Output

Following is the output −

Array has a slice element: 3

Example 3

In below example, defined two functions, arrSlice and strSlice, and used the slice() function to slice the element of collection −

fun arrSlice(array: Array<Any>) {
   println("${array.slice(2..5 step 2)}")
   println("${array.slice(1 ..3)}")
}

fun strSlice(string: String){
   println(string.slice(1..14))
   println(string.slice(20 downTo 0))
}

fun main(args: Array<String>){
   var arr = arrayOf<Any>(1, 3, 4, "tutorialspoint", "Hyderabad", 'A')
   var str = "The quick brown fox jumps over the lazy dog"

   //Calling Array function
   arrSlice(arr);

   //Calling String function
   strSlice(str);
}

Output

Following is the output −

[4, Hyderabad]
[3, 4, tutorialspoint]
he quick brown
j xof nworb kciuq ehT
kotlin_arrays.htm
Advertisements