Kotlin – Create Empty Array

To create an empty array in Kotlin, use arrayOf() function. arrayOf() function creates an array of specified type and given elements. If no elements are given as arguments, then arrayOf() returns an empty array.

Syntax

The syntax to create an empty array of type Int is

arrayOf<Int>()

The syntax to create an empty array of type String is

arrayOf<String>()

Examples

In the following program, we create an empty array of Int elements. To programmatically check if this array is empty or not, we can use isEmpty() method.

Refer Kotlin – Array.isEmpty() tutorial.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf<Int>()
    if (arr.isEmpty()) {
        println("An empty array.")
    } else {
        println("Not an empty array.")
    }
}

Output

An empty array.

Now, let us create an empty array of Strings.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf<String>()
    if (arr.isEmpty()) {
        println("An empty array.")
    } else {
        println("Not an empty array.")
    }
}

Output

An empty array.

Similarly, we can create an empty Array of any datatype using arrayOf() function.

Conclusion

In this Kotlin Tutorial, we learned how to create an empty Array of specified datatype using arrayOf() function, with examples.