Create an empty array in Kotlin
This article explores different ways to create an empty array in Kotlin.
1. Using emptyArray() function
The standard way to get an empty array is to use the emptyArray() function.
|
1 2 3 4 5 |
fun main() { val emptyArray : Array<Int> = emptyArray() println(emptyArray.size) // 0 } |
This can be shortened to:
|
1 2 3 4 5 |
fun main() { val emptyArray = emptyArray<Int>() println(emptyArray.size) // 0 } |
2. Using arrayOf() function
If you need an empty array instance, you can also use the arrayOf() function with no values.
|
1 2 3 4 5 |
fun main() { val emptyArray : Array<Int> = arrayOf() println(emptyArray.size) // 0 } |
We can simplify the declaration to:
|
1 2 3 4 5 |
fun main() { val emptyArray = arrayOf<Int>() println(emptyArray.size) // 0 } |
3. Using arrayOfNulls() function
You can get an empty array of nulls using the arrayOfNulls function.
|
1 2 3 4 5 |
fun main() { val emptyArray : Array<Int?> = arrayOfNulls(0) println(emptyArray.size) // 0 } |
Similar to the previous approach, we can rewrite this as:
|
1 2 3 4 5 |
fun main() { val emptyArray = arrayOfNulls<Int?> (0) println(emptyArray.size) // 0 } |
4. Using Array Constructor
Finally, you can use the Array constructor to get an empty array, as shown below:
|
1 2 3 4 5 |
fun main() { val emptyArray = Array(0) { 0 } println(emptyArray.size) // 0 } |
That’s all about creating 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 :)