How to initialize an array in Kotlin with values?

Lars Blumberg picture Lars Blumberg · Jul 12, 2015 · Viewed 215.3k times · Source

In Java an array can be initialized such as:

int numbers[] = new int[] {10, 20, 30, 40, 50}

How does Kotlin's array initialization look like?

Answer

Maroun picture Maroun · Jul 12, 2015
val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)

See Kotlin - Basic Types for details.

You can also provide an initializer function as a second parameter:

val numbers = IntArray(5) { 10 * (it + 1) }
// [10, 20, 30, 40, 50]