Kotlin emptyArray()

Kotlin emptyArray() Function

The Kotlin emptyArray() function in Kotlin is used to create an empty array of a specified type.

In this tutorial, you shall learn the syntax of Kotlin emptyArray() function, and how to use it with examples.

Syntax

The syntax of emptyArray() function is

fun <T> emptyArray(): Array<T>

The emptyArray() function returns a new array of type T with zero elements.

Example 1: Creating an Empty Integer Array using emptyArray()

In this example, we’ll use emptyArray() to create an empty array of integers.

Kotlin Program

fun main() {
    val emptyIntArray = emptyArray<Int>()
    println("Empty Integer Array: ${emptyIntArray.joinToString()}")
}

Output

Empty Integer Array: 

The output shows an empty array of integers created using emptyArray().

Example 2: Creating an Empty String Array using emptyArray()

Let’s use emptyArray() to create an empty array of strings.

Kotlin Program

fun main() {
    val emptyStringArray = emptyArray<String>()
    println("Empty String Array: ${emptyStringArray.joinToString()}")
}

Output

Empty String Array: 

The output shows an empty array of strings created using emptyArray().

Summary

In this tutorial, we have seen the syntax of Kotlin emptyArray() function, and how to use it to create an empty array of a specified type, with examples.