This article covers different ways to declare and initialize two-dimensional arrays in Kotlin.

1. Using arrayOf() function

The most common way to declare and initialize arrays in Kotlin is the arrayOf() function. To get a two-dimensional array, each argument to the arrayOf() function should be a single dimensional array. This is demonstrated below:

Download Code

 
The above code will result in the following matrix:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

 
You can use intArrayOf() for integers, doubleArrayOf() for a double, longArrayOf() for a long, charArrayOf() for the character array, and so on.

2. Array constructor

You can also declare and initialize two-dimensional arrays with the help of an Array constructor. The Array constructor takes the size of the first dimension and an init block. Consider the following code:

Download Code

 
This will result in a 3×4 matrix with a default value of 0 assigned to each element since no initializer is supplied.

[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]

 
To initialize the matrix with a fixed value, you can do like:

Download Code

 
This will result in a 3×4 matrix with all elements initialized with value 1.

[1, 1, 1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1]

 
You can also initialize your matrix with a lambda, as shown below. This is often useful to fill the matrix with some dynamic value based on the x and y index.

Download Code

 
Output:

[0, 1, 2, 3]
[1, 2, 3, 4]
[2, 3, 4, 5]

 
Note you can use the IntArray for integers, DoubleArray for a double, LongArray for a long, CharArray for the character array, and so on.

3. Using arrayOfNulls() function

Now with the arrayOfNulls() function, you can declare a two-dimensional array by only specifying the first dimension:

Download Code

 
This will result in the following matrix:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

4. Jagged Array

Finally, you can also initialize the columns with different lengths. The resultant array is called a jagged array, whose elements can have different dimensions and sizes. Following is a simple example demonstrating the jagged arrays:

Download Code

 
This will result in the following two-dimensional ragged array:

[1, 2, 3]
[4, 5]
[6, 7, 8, 9]

That’s all about declaring and initializing a two-dimensional array in Kotlin.