Declare an empty array in Kotlin
This article explores different ways to declare an empty array in Kotlin.
1. Using emptyArray() function
The standard approach in Kotlin to get an empty array of the specified type is using the emptyArray() function.
|
1 2 3 4 |
fun main() { val array = emptyArray<Int>() println(array.contentToString()) // [] } |
2. Standard library function
Alternatively, we can use the Kotlin standard library function to generate an empty array. There are several functions to construct an array, each for respective data types – doubleArrayOf(), floatArrayOf(), longArrayOf(), intArrayOf(), charArrayOf(), shortArrayOf(), byteArrayOf(), and booleanArrayOf().
|
1 2 3 4 |
fun main() { val array: IntArray = intArrayOf() println(array.contentToString()) // [] } |
To create a typed array, use the arrayOf<T>() function:
|
1 2 3 4 |
fun main() { val array: Array<String> = arrayOf<String>() println(array.contentToString()) // [] } |
3. Array constructor
We can also use the array constructor with the specified size 0 to create an empty array.
|
1 2 3 4 |
fun main() { val array = IntArray(0) println(array.contentToString()) // [] } |
To create a typed array, use the Array constructor as follows:
|
1 2 3 4 |
fun main() { val array: Array<Int> = Array(0) {0} println(array.contentToString()) // [] } |
We can even create an empty two-dimensional array containing non-empty arrays. For example, the following code creates a two-dimensional array of length 0, containing IntArray values:
|
1 2 3 4 |
fun main() { val array = Array(0) { IntArray(1) } println(array.contentDeepToString()) // [] } |
4. Using arrayOfNulls() function
Finally, we can use the arrayOfNulls() function to create an array of the specified size and the specified type, initialized with null.
|
1 2 3 4 |
fun main() { val array = arrayOfNulls<IntArray>(0) println(array.contentDeepToString()) // [] } |
That’s all about declaring an empty array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)