Use arrays in Kotlin when you have specialized low-level requirements that you need to meet. For example, if you have performance requirements beyond what is needed for regular applications, or you need to build custom data structures. If you don't have these sorts of restrictions, use collections instead.
Collections have the following benefits compared to arrays
Collections can be read-only, which gives you more control and allows you to write robust code that has a clear intent.
It is easy to add or remove elements from collections. In comparison, arrays are fixed in size. The only way to add or remove elements from an array is to create a new array each time, which is very inefficient:
You can use the equality operator (==) to check if collections are structurally equal. You can't use this operator for arrays. Instead, you have to use a special function, which you can read more about in Compare arrays.
To compare whether two arrays have the same elements in the same order, use the .contentEquals() and .contentDeepEquals() functions:
To create arrays in Kotlin, you can use:
functions, such as arrayOf(), arrayOfNulls() or emptyArray().
the Array constructor.
This example uses the arrayOf() function and passes item values to it:
val simpleArray = arrayOf(1, 2, 3)
println(simpleArray.joinToString())
This example uses the arrayOfNulls() function to create an array of a given size filled with null elements:
val nullArray: Array<Int?> = arrayOfNulls(3)
println(nullArray.joinToString())
// null, null, null
This example uses the emptyArray() function to create an empty array :
var exampleArray = emptyArray<String>()
You can specify the type of the empty array on the left-hand or right-hand side of the assignment due to Kotlin's type inference.For example:
var exampleArray = emptyArray<String>()
var exampleArray: Array<String> = emptyArray()
The Array constructor takes the array size and a function that returns values for array elements given its index:
If you use the Array class with primitive values, these values are boxed into objects. As an alternative, you can use primitive-type arrays, which allow you to store primitives in an array without the side effect of boxing overhead:
Better to use primitive type array to get performance faster as unboxing takes place when an normal array store objects and convert into the premitive type