Arrays in Kotlin

In Kotlin, an array is a fixed-size collection of elements of a specific type. While arrays are useful in some scenarios, Kotlin also provides more flexible collection types like Lists that are commonly used in typical Kotlin code.

fun main() {
    // Here we create an array `a` that will hold exactly 5 integers.
    // By default, an array is initialized with null values for object types,
    // or zero values for primitive types like Int.
    val a = IntArray(5)
    println("emp: ${a.contentToString()}")

    // We can set a value at an index using the array[index] = value syntax,
    // and get a value with array[index].
    a[4] = 100
    println("set: ${a.contentToString()}")
    println("get: ${a[4]}")

    // The size property returns the length of an array.
    println("size: ${a.size}")

    // Use this syntax to declare and initialize an array in one line.
    val b = intArrayOf(1, 2, 3, 4, 5)
    println("dcl: ${b.contentToString()}")

    // Kotlin doesn't have a built-in way to create arrays with specific indices initialized,
    // but we can achieve a similar effect using the Array constructor with a lambda.
    val c = IntArray(5) { i -> when(i) {
        0 -> 100
        3 -> 400
        4 -> 500
        else -> 0
    }}
    println("idx: ${c.contentToString()}")

    // Array types are one-dimensional, but you can compose types to build
    // multi-dimensional data structures.
    val twoD = Array(2) { IntArray(3) }
    for (i in 0 until 2) {
        for (j in 0 until 3) {
            twoD[i][j] = i + j
        }
    }
    println("2d: ${twoD.contentDeepToString()}")

    // You can create and initialize multi-dimensional arrays at once too.
    val anotherTwoD = arrayOf(
        intArrayOf(1, 2, 3),
        intArrayOf(4, 5, 6)
    )
    println("2d: ${anotherTwoD.contentDeepToString()}")
}

Note that arrays appear in the form [v1, v2, v3, ...] when printed with contentToString() or contentDeepToString() for multi-dimensional arrays.

When you run this program, you’ll see output similar to this:

emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
size: 5
dcl: [1, 2, 3, 4, 5]
idx: [100, 0, 0, 400, 500]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [4, 5, 6]]

In Kotlin, arrays are less commonly used than in some other languages, as the standard library provides powerful and flexible collection types like List, Set, and Map. However, arrays can still be useful in scenarios where you need a fixed-size collection or when working with Java APIs that expect arrays.