Kotlin Arrays

Kotlin Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To create an array in Kotlin, use the arrayOf() function, and place the values in a comma-separated list inside it.

Create an Array

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")

Access the Elements of an Array

You can access an array element by referring to the index number, inside square brackets [].

Important: Array indexes start with 0: [0] is the first element, [1] is the second element, etc.

Accessing Elements

val cars = arrayOf("Volvo", "BMW", "Ford")
println(cars[0])  // Outputs Volvo

Change an Array Element

To change the value of a specific element, refer to the index number:

cars[0] = "Opel"
println(cars[0])  // Now outputs Opel