Declaring, Initializing, and Using Key Functions of Kotlin Arrays

Introduces how to declare and initialize arrays.

Array

Create an array with arrayOf(). The number of elements in an array is fixed, but arrays provide good performance.

fun main() {
    val nums = arrayOf(1, 2, 3)
    val cols = arrayOf("Red", "Green", "Blue")

    for (n in nums) { println(n) }
    for (c in cols) { println(c) }
}

Output:

1
2
3
Red
Green
Blue

As shown below, if you specify the Array<Int> type when declaring the variable, you can omit the type in the later <>.

val array: Array<Int> = emptyArray<>()

You can access elements of an array with square brackets [...], and array indexes start at 0.

println(nums[0])
println(cols[1])

Declaring an Empty Array

You can declare an empty array of a specific type with the following functions.

val array1 = emptyArray<Int>()
val array2 = arrayOf<Int>()
fun main() {
    val array1 = emptyArray<Int>()
    println("array1: ${array1.contentToString()}")

    val array2 = arrayOf<Int>()
    println("array2: ${array2.contentToString()}")
}

Output:

array1: []
array2: []

Setting Initial Values When Declaring an Array

You can set initial values in an array with arrayOf<Type>(values). Because the type can be inferred from (values), <Type> can be omitted.

fun main() {
    val array1 = arrayOf<Int>(1, 2, 3, 4)
    println("array1: ${array1.contentToString()}")

    val array2 = arrayOf("Red", "Green", "Blue")
    println("arr: ${array2.contentToString()}")
}

Output:

array1: [1, 2, 3, 4]
array2: [Red, Green, Blue]

Initializing an Array with the Same Value

Array(size) { value } creates an array with the size set by size and assigns the specified value to every element.

fun main() {
    val array = Array(3) { 20 }
    println("array: ${array.contentToString()}")
}

Output:

array: [20, 20, 20]

Initializing an Array with Consecutive Numbers

Array(size) { lambda } creates an array with the size set by size, and every element is set to the return value of lambda.

The it passed to lambda becomes the element’s index value, so you can initialize an array with consecutive numbers as shown below.

fun main() {
    val array1 = Array(5) { it -> it }
    println("array1: ${array1.contentToString()}")

    val array2 = Array(5) { it -> it + 10 }
    println("array2: ${array2.contentToString()}")
}

Output:

array1: [0, 1, 2, 3, 4]
array2: [10, 11, 12, 13, 14]

Initializing an Array with Null

You can create an array filled with null by using arrayOfNulls<Type>(size).

fun main() {
    val array = arrayOfNulls<Int>(5)
    println("array: ${array.contentToString()}")
}

Output:

array: [null, null, null, null, null]

Declaring Primitive Type Arrays

Kotlin provides primitive type arrays such as IntArray, BooleanArray, DoubleArray, and LongArray.

When creating these arrays, you can use functions such as intArrayOf() and booleanArrayOf().

fun main() {
    val iniArray: IntArray = intArrayOf(1, 2, 3)
    println("iniArray: ${iniArray.contentToString()}")

    val booleanArray: BooleanArray = booleanArrayOf(true, true, false)
    println("booleanArray: ${booleanArray.contentToString()}")

    val doubleArray: DoubleArray = doubleArrayOf(1.2, 2.3, 3.4)
    println("doubleArray: ${doubleArray.contentToString()}")
}

Output:

iniArray: [1, 2, 3]
booleanArray: [true, true, false]
doubleArray: [1.2, 2.3, 3.4]

Key Functions

forEach Function

The forEach function can iterate over a list.

fun main() {
    val array = arrayOf(1, 2, 3, 4, 5)

    // Using it as a lambda.
    array.forEach({ element ->
        print("$element,")
    }) // => 1,2,3,4,5
    println()

    // The parentheses '()' can be omitted.
    array.forEach { element ->
        print("$element,")
    }
    println()

    // You can receive the object with it instead of a lambda parameter.
    array.forEach {
        print("$it,")
    } // => 1,2,3,4,5
}

Output:

1,2,3,4,5,
1,2,3,4,5,
1,2,3,4,5,

filter Function

The filter function applies a condition to a list and returns a new list containing the elements that match the condition.

fun main() {
    val array = arrayOf(1, 2, 3, 4, 5) // => Creates the 1,2,3,4,5 array.

    // Returns the elements that satisfy the filter condition.
    array.filter({ e -> e % 2 == 0 }).forEach { println(it) } // => 2,4

    // The parentheses '()' can be omitted.
    array.filter { e -> e % 2 == 0 }.forEach { println(it) } // => 2,4

    // You can receive the object with 'it' without using a lambda parameter.
    array.filter { it % 2 == 0 }.forEach { println(it) } // => 2,4

}

Output:

2,4,
2,4,
2,4,

map Function

The map function lets you transform and receive the elements of a list.

// Defines a class with a name and age
private class Person(val name: String, val age: Int)

fun main() {
    val array = arrayOf(
        Person("Charlie", 20),
        Person("devkuma", 31),
        Person("kimkc", 42),
    )

    // You can receive the user instance as a lambda parameter.
    array.map({ user -> user.name }).forEach { print("${it},") }
    println()

    // The parentheses '()' can be omitted.
    array.map { user -> user.name }.forEach { print("${it},") }
    println()

    // You can receive the object with 'it' (this 'it' points to the user instance).
    array.map { it.name }.forEach { print("${it},") }
}

Output:

Charlie,devkuma,kimkc,
Charlie,devkuma,kimkc,
Charlie,devkuma,kimkc,

sum Function

The sum function adds the input numbers together.

fun main() {
    // Creates an Array<Int> instance.
    val array = arrayOf(1, 2, 3, 4, 5)

    // Adds them together (1 + 2 + 3 + 4 + 5).
    println(array.sum()) // => 15
}

Output:

15

take Function

The take function takes only the specified number of elements from a list.

fun main() {
    val array = arrayOf(1, 2, 3, 4, 5)
    array.take(1).forEach { print(it) } // => 1
    println()
    array.take(2).forEach { print(it) } // => 1, 2
    println()
    array.take(3).forEach { print(it) } // => 1, 2, 3
    println()
    array.take(4).forEach { print(it) } // => 1, 2, 3, 4
    println()
    array.take(5).forEach { print(it) } // => 1, 2, 3, 4, 5
}

Output:

1
12
123
1234
12345

drop Function

The drop function removes the specified number of elements from the front of a list and returns the remaining elements.

fun main() {
    val array = arrayOf(1, 2, 3, 4, 5)
    array.drop(1).forEach{print(it)} // => 2, 3, 4, 5
    println()
    array.drop(2).forEach{print(it)} // => 3, 4, 5
    println()
    array.drop(3).forEach{print(it)} // => 4, 5
    println()
    array.drop(4).forEach{print(it)} // => 5
    println()
    array.drop(5).forEach{print(it)} // => Empty Array
}

Output:

2345
345
45
5