Arrays in Kotlin

You are here:
Estimated reading time: 6 min

In this tutorial, we will be learning how to use Arrays in Kotlin.

We will talk about different ways of initializing arrays in Kotlin, traversing arrays using loops, and different functions in Kotlin’s Array Class.

Definition

An array is a collection of homogenous elements (elements of similar data type), stored in contiguous memory locations. They are also called linear data structures because of their continuous memory allocation.

Arrays are Index-based, and Indices start from 0.

Arrays are also known as Static Data Structures because the size of the array must be specified at the time of declaration i.e. the length of the array is defined at the time of creation.

Unlike C, arrays in Kotlin are not a primitive data type. Instead, they are instances (objects) of the class Array.

Initialization

Initializing Arrays using the arrayOf() function

We can create an array using the arrayOf() library function.

The arrayOf function takes array elements as parameters and returns an array.

We can pass array elements as parameters, such that arrayOf(1,2,3,4,5) returns [1,2,3,4,5].

    var array1 = arrayOf(1,2,3,4,5) //array of Int objects
    var Fruits = arrayOf("Apples","Oranges","Bananas","Pineapples") 
    //array of String objects
    var numbers = arrayOf(11L,22L,33L,44L,55L) //array of Long objects

This is an entirely general mechanism, that can be used to create an array of any data type.

In arrays created using the arrayOf() library function, the array elements are of boxed types. For example, in an array created using arrayOf(1,2,3,4,5), the digits 1-5 are not integers. Rather, they are instances(objects) of the Integer class i.e. they are Int objects. They are not primitive data types.

As the arrayOf() method of creating arrays is completely general i.e. it can be used to create arrays of any data type, the Kotlin compiler implicitly determines the type of the array.

We can also specify the type of the array explicitly using the arrayOf() function, we can declare them as shown below:

    var array1 = arrayOf<Int>(1,2,3,4,5) //array of Int objects
    var Fruits = arrayOf<String>("Apples","Oranges","Bananas","Pineapples")
    //array of String objects
    var numbers = arrayOf<Long>(11,22,33,44,55) //array of Long objects

NOTE:

Using the arrayOf function, arrays of Any type can also be created, wherein each array element will be an object of the Any class.

fun main(){
    var anyArray = arrayOf("Hello",1,2,3)
    var anyArrayExplicit = arrayOf<Any>("Books","Bags",1L,2L,11,22)
}

Looking at the above example, it may seem as if we are creating arrays of elements having different data types but that is NOT the case.

Keep in mind that these elements are of the Any type.

With respect to the above example:

  • anyArray –

“Hello” is not an object of class String.

1,2,3 are not objects of class Int.

  • anyArrayExplicit –

“Books”, “Bags” are not objects of class String.

1L,2L are not objects of class Long.

11,22 are not objects of class Int.

Rather, all the above elements are objects of the Any class. Hence, all of them have the same data type.

Initializing Primitive Arrays

The arrayOf() function will autobox the passed elements to their corresponding object wrapper classes.

This is detrimental to performance.

To create arrays of primitive data types, Kotlin provides us utility functions such as intArrayOf(), charArrayOf(), booleanArrayOf(), longArrayOf(), floatArrayOf(), shortArrayOf(), byteArrayOf().

fun main(){
    var Numbers = intArrayOf(1,2,3,4,5)
    var Characters = charArrayOf('a','b','$','1')
    var LongNumbers = longArrayOf(11,22,33,44)
    var BooleanVals = booleanArrayOf(true, false)
}

In arrays created using these functions, the elements are of primitive data types. For example, in array created using intArrayOf(1,2,3,4,5), the numbers 1-5 are raw integers.

Arrays created using this method are more efficient and boost the performance of the project.

Also, these primitive type arrays are useful when a project contains Kotlin as well as Java code. Kotlin type arrays can be passed to the Java code as primitive type arrays.

Initializing Large Arrays

To define arrays of larger size, arrayOf() library method is not very efficient.

In other languages such as C, C++, to define arrays of large sizes, we will declare an array of a particular size and then initialize its elements later, usually through a for loop. But, this can not be done in Kotlin, as Kotlin does not allow declaration and initialization to be separate i.e. it does not allow for uninitialized variables to be declared.

A given variable must either be initialized at the time of declaration or it must be declared to be nullable.

Therefore, to create arrays of large sizes, there are two approaches:

Initializing Large Arrays using arrayOfNulls()

We can create an array of nullable types, all initialized to null using the arrayOfNulls() factory function.

Syntax

var ArrayName = arrayOfNulls<type>(size)

Examples

fun main(){
    var Array1 = arrayOfNulls<Int>(500)
}

This creates an array named ‘Array1’ containing 500 objects of class Int, all initialized to null.

This array can later be initialized using a simple for loop as shown below:

fun main(){
    var Array1 = arrayOfNulls<Int>(500)
    var arrayVal=1
    for(i in Array1.indices){
        Array1[i]=arrayVal
        arrayVal++
    }
}

This will initialize array elements with values from 1-500.

Note:

If an array of nullable types is declared, and an element from that array is used in an expression, either we have to make sure that the value is assigned to another nullable type, or if it is not being assigned to another nullable type, then we have to check beforehand to make sure that the array element’s value is not null.

fun main(){
    var Array1 = arrayOfNulls<Int>(500)
    var num = 5
    num = Array1[0]
}

In the above example, an error will be generated.

error: type mismatch: inferred type is Int? but Int was expected
num = Array1[0]

To avoid this, we can either assign a value to the element Array1[0] before using it in an expression, or we can declare the variable num to be nullable.

Initializing Large Arrays using Array() Constructor

The Kotlin Array() Constructor expects two parameters, the size of the array and the init.

init consists of a lambda expression that returns the value of each element of the array, given its index.

fun main(){
    var Array1 = Array(100,{i -> i+1})
    //OR
    var Array2 = Array(100){i -> i*2}
    println(Array1[99])
    println(Array2[99])
}

Note:

When using an array of Primitive types, it is not necessary to initialize the array.

fun main(){
    var Array1 = intArrayOf(50)
}

Kotlin Array Methods

set() function

The set() function of the Array class can be used to change the value of an array at a given index. It takes two parameters, the index whose value is to be changed and the new value which is to be assigned at that index.

fun main(){
    var Array1 = intArrayOf(1,2,3,4,5,6,7,8,9,10)
    println(Array1[0]) //will print 1
    println(Array1[5]) //will print 6
    Array1.set(0,99)
    Array1[5]=66
    println(Array1[0]) //will print 99
    println(Array1[5]) //will print 66
}

get() function

The get() function of the Array class can be used to retrieve the value of an array element. It takes the index of the array element whose value is to be retrieved as its parameter.

fun main(){
    var Array1 = intArrayOf(1,2,3,4,5,6,7,8,9,10)
    println(Array1[0]) //will print 1
    println(Array1.get(9)) //will print 10
}

plus() function

The plus() function takes a single element which is to be added to an array A1 as a parameter and creates a new array with the elements of the array A1, as well as, the added element. (Remember that arrays are fixed size; therefore, a new array is created).

fun main(){
    var Array1 = intArrayOf(1,2,3,4,5,6,7,8,9,10)
    var Array2 = Array1.plus(99)
}

sliceArray() function

The sliceArray method is used to create a slice from an array.

fun main(){
    var Array1 = intArrayOf(1,2,3,4,5,6,7,8,9,10)
    var slicedArray1 = Array1.sliceArray(1..5)
}

first() and last() functions

first() and last() functions are used to retrieve the first and last elements of an array.

fun main(){
    var Array1 = intArrayOf(1,2,3,4,5,6,7,8,9,10)
    println(Array1.first())
    println(Array1.last())
}

average(), count(), sum(), min(), max() functions

fun main(){
    var Array1 = intArrayOf(1,2,3,4,5,6,7,8,9,10)
    println(Array1.average()) //Will give average of all numbers
    println(Array1.count()) //Will give number of elements
    println(Array1.sum()) //Will give sum of all elements of an array
    println(Array1.min()) //Will give smallest element of an array
    println(Array1.max()) //Will give largest element of an array
}

find() and findLast() functions

The find() function takes a condition as a parameter and returns the value of the first array element that satisfies that condition.

The findLast() function works the same way as find(), except it returns the value of the last array element that satisfies the condition.

fun main(){
    var Array1 = intArrayOf(11,2,8,1,6,44,14,3)
    var firstEvenVal = Array1.find{it%2==0}
    println(firstEvenVal)
    var lastEvenVal = Array1.findLast{it%2==0}
    println(lastEvenVal)
}

all() and any() functions

The all() function takes a condition as a parameter and returns true if all the elements of the array satisfy that condition. Else, false is returned. The any() function works similarly as all() except it returns true if any one element of the array satisfies the condition. False is returned if none of the elements of the array satisfy the condition.

fun main(){
    var Array1 = intArrayOf(11,2,8,1,6,44,14,3)
    var areAllEven = Array1.all{it%2==0}
    var isAnyEven = Array1.any{it%2==0}
    println(areAllEven) //returns False
    println(isAnyEven) //return True
}

Kotlin Array Traversal

fun main(){
    var Array1 = intArrayOf(1,2,3,4,5,6,7,8,9,10)
    for(i in Array1){
        println(i)
    }
    //using arrayName.indices
    for(i in Array1.indices){
        println(Array1[i])
    }
    //using withindex() function
    for((index,value) in Array1.withindex()){
        println("Value at $index is $value")
    }
}

Kotlin Array Sorting using sortedArray() function

The sortedArray() function sorts the array through which the function is called and returns a new array with the sorted values i.e. the sorting is not done in place.

fun main(){
    var Array1 = intArrayOf(11,2,8,1,6,44,14,3)
    var sortedArray1 = Array1.sortedArray()
    for(i in sortedArray1){
        println(i)
    }
}

The above example will print 1 2 3 6 8 11 14 44.

Arrays in Kotlin are quite different than Arrays in Java. To learn more about the differences between Java and Kotlin, check out our article on Java vs Kotlin: https://kotlintutorials.com/reference/kotlin-vs-java/

Check out our list of comprehensive and in-depth Kotlin articles: https://kotlintutorials.com/

References:

https://kotlinlang.org/docs/reference/basic-types.html

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/index.html

https://en.wikipedia.org/wiki/Kotlin_(programming_language)

Was this article helpful?
Dislike 0
Views: 11