Kotlin arrayOfNulls() – Examples

Kotlin arrayOfNulls()

The Kotlin arrayOfNulls() function is used to create an array of a specified size with all elements initialized to null.

Syntax

The syntax of arrayOfNulls() function is

fun <T> arrayOfNulls(size: Int): Array<T?>

where

ParameterDescription
sizeThe size of the array to be created.
Parameters of arrayOfNulls() function

and T is the type of elements in the array (can be nullable).

Return Value

The function returns an Array object of specified size with all elements set to null.

Example 1: Basic Usage of arrayOfNulls()

In this example we shall create an array of integers with size 5, where all elements are initialized to null, using arrayOfNulls() function.

Call arrayOfNulls() function and pass 5 as argument for size parameter.

Kotlin Program

fun main() {
    val nullArray = arrayOfNulls<Int>(5)

    for (element in nullArray) {
        println(element)
    }
}

Output

null
null
null
null
null

Example 2: Array of Nullable Custom Objects using arrayOfNulls()

This example uses the arrayOfNulls() function to create an array of nullable custom objects (Person) with size 3, where all elements are initialized to null.

Kotlin Program


data class Person(val name: String, val age: Int)

val nullablePeople = arrayOfNulls<Person>(3)

for (person in nullablePeople) {
    println(person)
}

Output

null
null
null

Summary

In this tutorial, we have learnt about Kotlin arrayOfNulls() function, its syntax, and show to use this function to create an array for later assignment or when you want to initialize an array with nullable elements.