What is the use of emptyArray () in Kotlin

I studied emptyArray() in Kotlin, but I cannot assign values โ€‹โ€‹to it (which is obvious), and I cannot set its size. What is the use of emptyArray in Kotlin?

+5
source share
4 answers

The emptyArray () function returns an empty array of size 0. It takes no parameters (neither size, nor elements). you can use it as rvalue in assignment operations. You can use an empty array to discard all values โ€‹โ€‹in pre-existing arrays and set it to 0. Note: it is better to return empty than return an array of zeros, since it will not throw zero point exceptions in further operations.

 var array=arrayOf(1,2,3,4,5); array = emptyArray() //The array datais dumped and size is set to 0; array = arrayOf(0,1,2) 
0
source

Like the java.util.Collections.emptyList() methods and its counterparts for Maps , etc., these methods are convenient when you call a method that takes an array / collection as an argument, but you do not want / should not provide any elements in this collection. You can either create a new empty array / collection, or use one of the helper methods.

If the above use case is very common in your scenario, you protect the memory with helpers, as always the same instance is reused, and not to create new instances over and over again. Otherwise, it is basically โ€œsyntactic candyโ€, which makes your code more understandable and understandable.

+4
source

There are times when you want to fall back to empty arrays or empty lists. For instance:

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

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

So yes, it is empty, and you cannot add to it as soon as the JVM array expands after allocation.

+4
source

Arrays are containers with a fixed size. The emptyArray() function creates an array of length 0, and you really can't do much with this. You cannot store anything in it, and you cannot resize it.

A common use case in which you need an empty array will be the default value for the property, which will be set to another array at a later point. This might be better than storing null in this property by default, because you don't have to deal with the possible null value when your code uses an array. For example, you can safely iterate over an empty array.


For a simple example:

 class NumberHolder { var numbers: Array<Int> = emptyArray() fun printNumbers() { numbers.forEach { println(it) } } } 

Using this class will look something like this:

 val nh = NumberHolder() nh.printNumbers() // prints nothing nh.numbers = arrayOf(1, 2, 3) nh.printNumbers() // prints 1, 2, and 3 on separate lines 
0
source

Source: https://habr.com/ru/post/1268300/


All Articles