๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin Array Methods

Array tools are built-in actions and values that work on an array. The size of an array counts the values it holds.

size counts the values

The array holds four numbers. The size print shows 4.

fun main() {
    val scores = intArrayOf(10, 20, 30, 40)
    println(scores.size)
}

indices walks every position

The loop visits each valid index in order. Each print places the index beside the value at that index.

fun main() {
    val scores = intArrayOf(10, 20, 30)
    for (index in scores.indices) {
        println("${index} ${scores[index]}")
    }
}

lastIndex picks the last value

The array holds three values and its indexes run from 0 to 2. The three prints show size and lastIndex and the value at lastIndex.

fun main() {
    val scores = intArrayOf(10, 20, 30)
    println(scores.size)
    println(scores.lastIndex)
    println(scores[scores.lastIndex])
}

sort places values in order

The first print shows the stored order. The second print shows the same array after sort has placed the numbers in order.

fun main() {
    val scores = intArrayOf(30, 10, 20)
    println(scores.contentToString())
    scores.sort()
    println(scores.contentToString())
}

Example

fun main() {
    val marks = intArrayOf(40, 10, 30, 20)
    println(marks.size)
    println(marks.lastIndex)
    marks.sort()
    println(marks.contentToString())
}

Key points

  • .size: the count of values in an array.
  • .indices: the range of valid indexes for an array.
  • .lastIndex: the index of the last value in an array.
  • lastIndex is one less than size.
  • Use sort to place the values of an array in order.

In this example, marks holds four numbers. The first print shows its size as 4. The second print shows its lastIndex as 3. The sort call places the values in order. The last print shows [10, 20, 30, 40].

Note

sort changes the stored array itself and builds no copy.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

An array holds five values. What is its lastIndex?