Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of emptyArray() in Kotlin

Tags:

kotlin

I was learning emptyArray() in Kotlin, but I can't assign values in it (which is for obvious) and neither I can set it's size. What is the use of emptyArray in Kotlin?

like image 985
Alok Panday Avatar asked May 28 '17 15:05

Alok Panday


1 Answers

There are cases where you want to fallback to an empty array or empty list. For example:

return someInputArray?.filterNotNull() ?: emptyArray()

In this case if I have a valid input array, I filter out null values, otherwise if the source array was null I return an empty array. Therefore an array is always returned instead of a null. Empty lists and arrays are probably more common than passing around nullable lists or arrays in Kotlin.

So yes, it is empty and you cannot add to it, just as no JVM array is expandable once allocated.

like image 136
Jayson Minard Avatar answered Nov 10 '22 05:11

Jayson Minard