2D Array in Kotlin

You may use this line of code for an Integer array.

val array = Array(row) { IntArray(column) }

This line of code is pretty simple and works like 1D array and also can be accessible like java 2D array.


Short Answer:

// A 6x5 array of Int, all set to 0.
var m = Array(6) {Array(5) {0} }

Here is another example with more details on what is going on:

// a 6x5 Int array initialise all to 0
var m = Array(6, {i -> Array(5, {j -> 0})})

The first parameter is the size, the second lambda method is for initialisation.


I have been using this one-liner when creating matrix

var matrix: Array<IntArray> = Array(height) { IntArray(width) }

You are trying to put your IntArrays inside another array to make it 2-dimensional. The type of that array cannot be intArray, which is why this fails. Wrap your initial arrays with arrayOf instead of intArrayOf.

val even: IntArray = intArrayOf(2, 4, 6)
val odd: IntArray = intArrayOf(1, 3, 5)

val lala: Array<IntArray> = arrayOf(even, odd)

Tags:

Arrays

Kotlin