kotlin

Create an empty Array in Kotlin

There are multiple ways to create an empty array in Kotlin. In this post, we are going to explain multiple methods that can be used to create array with no items in it.

// using arrayOf() function
val arr = arrayOf<String>()

// or
val arr: Array<String> = arrayOf()

We are using arrayof() function here to create an empty array in Kotlin. We are not adding any item to this array and if we execute arr.size, it will return 0.

Use emptyArray() function to create an empty array

We can also use Kotlin's built-in emptyArray() method to create an empty array. We can only make explicit empty arrays in Kotlin. It means you will have to define the type of values that the array will be adding or removing.

fun main() {
    val arr = emptyArray<Int>()
    
    println(arr.size) // -> 0
}

Or you can also use the below code

val arr: Array<Int> = emptyArray()

Create empty array using arrayOfNulls() function

We can also create an empty array in Kotlin using arrayOfNulls() function. Below is an example for that.

val arr: Array<String?> = arrayOfNulls(0)
    
println(arr.size) // -> 0

Or you can also use

val arr = arrayOfNulls<String?>(0)
    
println(arr.size) // -> 0
Was this helpful?