๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin Arrays

An array is a value that holds several values of one type in order. Each value sits at a numbered position called an index.

contentToString shows the values

contentToString builds text from the values in order. The print shows the three numbers inside brackets.

fun main() {
    val scores = intArrayOf(1, 2, 3)
    println(scores.contentToString())
}

One value by index

Index 1 picks the second value in the array. Indexes start at 0 so the first value sits at index 0.

fun main() {
    val names = arrayOf("Ana", "Bo", "Cy")
    println(names[1])
}

joinToString joins with a separator

The separator sits between each pair of values. The joined values print as one line with dashes between them.

fun main() {
    val scores = intArrayOf(1, 2, 3)
    println(scores.joinToString(" - "))
}

An array of strings prints its words

The same call works for text values. The print shows each word in order inside brackets.

fun main() {
    val words = arrayOf("red", "blue", "green")
    println(words.contentToString())
}

Example

fun main() {
    val temps = intArrayOf(18, 21, 19)
    println(temps.contentToString())
    println(temps[0])
    println(temps.joinToString(" - "))
}

Key points

  • arrayOf: a call that builds an array from the values given to it.
  • intArrayOf: a call that builds an array of whole numbers.
  • Use contentToString to print the values of an array in order.
  • Use joinToString to join the values of an array into one string.
  • Read one value by writing the array name and an index in square brackets.
  • Indexes start at 0 for the first value.

In this example, temps holds the numbers 18 and 21 and 19. The first print uses contentToString and shows [18, 21, 19]. The second print reads index 0 and shows 18. The last print joins the values with dashes and shows 18 - 21 - 19.

Note

Printing an array by itself shows a short reference code and not the values.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

An array holds the values 5 and 10 and 15 in order. What does printing the value at index 2 give?