Kotlin array basic operations

In this Kotlin example, we will see how to retrieve and modify array elements, create a slice, and get an index of an element.
All Kotlin examples at All Kotlin Examples.

Kotlin array basic operations example

The following example presents some basic operations with Kotlin arrays:
import java.util.Arrays

fun main() {

    val nums = arrayOf(1, 2, 3, 4, 5)
    println(nums.get(0))

    nums.set(0, 0)
    println(Arrays.toString(nums))

    val nums2 = nums.plus(1)
    println(Arrays.toString(nums2))

    val slice = nums.sliceArray(1..3)
    println(Arrays.toString(slice))

    println(nums.first())
    println(nums.last())
    println(nums.indexOf(5))
}
Output:
1
[0, 2, 3, 4, 5]
[0, 2, 3, 4, 5, 1]
[2, 3, 4]
0
5
4

All Kotlin examples at All Kotlin Examples.

Comments