Arrays
Arrays in Kotlin are represented by the Array
class. It has get()
and set()
functions that turn into []
by operator overloading conventions, and the size
property, along with other useful member functions:
To create an array, use the function arrayOf()
and pass the item values to it, so that arrayOf(1, 2, 3)
creates an array [1, 2, 3]
. Alternatively, the arrayOfNulls()
function can be used to create an array of a given size filled with null
elements.
Another option is to use the Array
constructor that takes the array size and the function that returns values of array elements given its index:
The []
operation stands for calls to member functions get()
and set()
.
Arrays in Kotlin are invariant. This means that Kotlin does not let us assign an Array<String>
to an Array<Any>
, which prevents a possible runtime failure (but you can use Array<out Any>
, see Type Projections).
Primitive type arrays
Kotlin also has classes that represent arrays of primitive types without boxing overhead: ByteArray
, ShortArray
, IntArray
, and so on. These classes have no inheritance relation to the Array
class, but they have the same set of methods and properties. Each of them also has a corresponding factory function: