arrayOfNulls()
Anonymous contributor
Published Nov 7, 2024
Contribute to Docs
In Kotlin, the arrayOfNulls()
function creates an array of a specified size with all elements initialized to null
. This function is useful for creating an array with a defined size when initial values are not yet available, allowing for values to be assigned later.
Syntax
fun <T> arrayOfNulls(size: Int): Array<T?>
T
: The type of elements in the array.size
: An integer specifying the size of the array to create.
It returns an Array<T?>
of the specified size, initialized with null
.
Example
The following example uses the arrayOfNulls()
function:
fun main() {// Create an array of size 5 with all elements initialized as nullval nullArray = arrayOfNulls<Int>(5)// Assign values to some elements in the arraynullArray[0] = 2nullArray[1] = 4// Print the array after assigning valuesprintln(nullArray.contentToString())}
This example results in the following output:
[2, 4, null, null, null]
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Kotlin on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Kotlin
Learn Kotlin, the expressive, open-source programming language developed by JetBrains.Beginner Friendly9 hours