How to initialize an array in Kotlin?

Small tutorial with code examples and video about arrays in Kotlin
18 August 2017   1703

What is array in Kotlin?

According to the official website, arrays in Kotlin are represented by the Array class, that has get and set functions (that turn into []by operator overloading conventions), and size property, along with a few other useful member functions:

class Array<T> private constructor() {
    val size: Int
    operator fun get(index: Int): T
    operator fun set(index: Int, value: T): Unit

    operator fun iterator(): Iterator<T>
    // ...

To create an array, we can use a library function arrayOf() and pass the item values to it, so that arrayOf(1, 2, 3) creates an array [1, 2, 3]. Alternatively, the arrayOfNulls() library function can be used to create an array of a given size filled with null elements.

Another option is to use a factory function that takes the array size and the function that can return the initial value of each array element given its index:

// Creates an Array<String> with values ["0", "1", "4", "9", "16"]
val asc = Array(5, { i -> (i * i).toString() })

As we said above, the [] operation stands for calls to member functions get() and set().

Note: unlike Java, 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.

How to initialize an array in Kotlin?

Kotlin also has specialized classes to represent arrays of primitive types without boxing overhead: ByteArrayShortArrayIntArray 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:

val x: IntArray = intArrayOf(1, 2, 3)
x[0] = x[1] + x[2]

The video above will get you familiar with arrays in Kotlin.

How to convert list to map in Kotlin

Two ways to convert list to map in Kotlin, with code examples
31 October 2017   507

For example, you have a list of strings like:

val list = listOf("a", "b", "c", "d")

and you need to convert it to a map, where the strings are the keys.

There are two ways to do this:

The first and most performant is to use associateBy function that takes two lambdas for generating the key and value, and inlines the creation of the map:

val map = friends.associateBy({it.facebookId}, {it.points})

The second, less performant, is to use the standard map function to create a list of Pair which can be used by toMap to generate the final map:

val map = { it.facebookId to it.points }.toMap()