Arrays
An array is a data structure that holds a fixed number of values of the same type or its subtypes. Array elements are ordered and accessed by index.
Kotlin provides the Array<T> class and primitive-type arrays.
When to use arrays
Use arrays for interoperability with Java APIs or low-level requirements. For example, if you have performance requirements beyond what is needed for regular applications, or you need to build custom data structures.
For most use cases, prefer collections instead.
Functionality | Arrays | Collections |
|---|---|---|
Size | Fixed | Depends on the type |
Read-only variant | No, always mutable | Yes ( |
Adding and removing elements | No native support. | Yes (mutable collections) |
Structural equality with | No, compares references. | Yes |
Primitive values | Primitive-type arrays store values | Usually boxed |
Java interoperability | Maps to | Maps to |
Functional-style filtering and | Limited | Extensive |
Learn how to convert arrays to collections.
Create arrays
To create arrays, you can use:
The
arrayOf(),arrayOfNulls(), oremptyArray()functions.The
Arrayconstructor.
Array with values
To create a typed array from a known set of values, use the arrayOf() function. Kotlin infers the type automatically:
Empty array
To create an array with no elements, use the emptyArray() function. You can specify the type of elements on the left-hand or right-hand side of the assignment:
Learn how to add elements to an array.
Array with nulls
To create an array of a given size filled with null elements, use the arrayOfNulls() function:
Array constructor
The Array constructor takes the array size and a function that returns values of array elements:
Nested arrays
To create a nested or multidimensional array, use an array of arrays. Nested arrays don't have to be the same type or the same size.
Primitive-type arrays
If you use the Array class with primitive values, the compiler boxes these values into objects. To avoid boxing overhead, you can use dedicated primitive-type arrays. They are not subclasses of the Array<T> class, but they provide a similar set of functions and properties.
Kotlin type | Java equivalent |
|---|---|
| |
| |
| |
| |
| |
| |
| |
|
To create a primitive-type array, use one of the following options:
Constructor functions:
fun main() { //sampleStart // Creates an Int array of size 5 with the values initialized to zero val primitiveTypeArray = IntArray(5) println(primitiveTypeArray.joinToString()) // 0, 0, 0, 0, 0 // Creates an Int array and takes an initializer function val squares = IntArray(5) { i -> i * i } println(squares.joinToString()) // 0, 1, 4, 9, 16 //sampleEnd }Factory functions:
fun main() { //sampleStart // Creates an Int array with 5 elements val numbers = intArrayOf(1, 2, 3, 4, 5) println(numbers.joinToString()) // 1, 2, 3, 4, 5 // Creates a Char array with 3 elements val characters = charArrayOf('K', 't', 'l') println(characters.joinToString()) // K, t, l // Creates a Double array with 3 elements val doubles = doubleArrayOf(0.22, 4.16, 0.5) println(doubles.joinToString()) // 0.22, 4.16, 0.5 //sampleEnd }
Work with arrays
Arrays support many of the same operations as collections, including iteration, searching, sorting, and transformations. In Kotlin, you can work with arrays by using them to pass a variable number of arguments to a function or perform operations on the arrays themselves. Find the most common properties and functions in the following table:
Member | Returns |
|---|---|
The number of elements | |
The range of valid indices | |
The last valid index | |
First and last element | |
| |
|
This section introduces some of the most commonly used operations.
Access and modify elements
To access and modify elements in an array, use the indexed access operator ([]):
You can also use the fill(element, fromIndex, toIndex) function to replace elements in a range in place. fromIndex is inclusive, and toIndex is exclusive:
In Kotlin, arrays are invariant. This means that Array<String> is not a subtype of Array<Any>. This prevents possible runtime type failures. To express covariance, use the Array<out Any> type projection:
Add and remove elements
Since arrays have a fixed size, they don't support the .add() and .remove() functions. To perform these operations, you need to create a new array. For that, you can use one of the following options:
Use the
.copyOffunction:fun main() { //sampleStart var arr = intArrayOf(0, 1, 2) arr = arr.copyOf(arr.size + 1) println(arr.joinToString()) // 0, 1, 2, 0 arr[arr.lastIndex] = 3 println(arr.joinToString()) // 0, 1, 2, 3 //sampleEnd }Use the
+or+=operators:fun main() { //sampleStart var arr = intArrayOf(0, 1, 2) arr += 3 println(arr.joinToString()) // 0, 1, 2, 3 arr = arr + intArrayOf(4, 5) println(arr.joinToString()) // 0, 1, 2, 3, 4, 5 //sampleEnd }
Compare arrays
To compare whether two arrays have the same elements in the same order, use the .contentEquals() and .contentDeepEquals() functions:
Transform arrays
Kotlin has many useful functions to transform arrays. This section highlights some of them. See the complete list in our API reference.
Sum
To return the sum of all elements in an array, use the .sum() function:
Sort and shuffle
You can sort the elements in the array according to their natural order with the .sort() function or randomly shuffle them with the .shuffle() function:
To get a new sorted array without modifying the original, use the .sortedArray() function instead.
Pass variable number of arguments to a function
In Kotlin, you can pass a variable number of arguments to a function via the vararg parameter. This is useful when you don't know the number of arguments in advance, like when formatting a message or creating an SQL query.
To pass an array containing a variable number of arguments to a function, use the spread operator (*). The spread operator passes each element of the array as individual arguments to your chosen function:
For more information, see Variable number of arguments (varargs).
Convert to collections
If you work with different APIs where some use arrays and some use collections, you can convert your arrays to collections and vice versa. For that, use the .toList(), .toSet(), and .toMap() functions. These functions copy the content from your array to the independent copy. They don't reflect subsequent changes to the array.
Convert to List or Set
To convert an array to a List or Set, use the .toList() and .toSet() functions:
Unless you are completely sure that the original array isn't changed or shared elsewhere, don't use .asList() and related as* functions. These functions wrap the original array instead of copying it. Therefore, changes to the array are reflected in the list and vice versa.
Convert to Map
To convert an array to a Map, use the .toMap() function.
You can convert only an array of Pair<K,V> to a Map. The first value of a Pair instance becomes a key, and the second becomes a value. If the same key appears more than once, the last value is used.
This example uses the infix notation to call the .to function to create tuples of Pair:
What's next?
Learn more about why we recommend using collections for most use cases in the Collections overview.
Learn about other basic types.
If you are a Java developer, read our Java to Kotlin migration guide for Collections.