Crew'row
Crew'row

Reputation: 3

Is there a way in Kotlin to create/initiolise an multidimensional array without giving it values

Hi I want to know if there is a short way to create an multidimensional array without preassinde values like in C# string[][] arr = string[5][]?

Upvotes: 0

Views: 37

Answers (1)

Sweeper
Sweeper

Reputation: 274565

string[][] arr = string[5][] in C# is not a multidimensional array, nor does it not have "preassigned values". It is a jagged array (this means that each inner array can be a different length), and has null as the initial (preassigned) values for each inner array.

To do the same in Kotlin, you'd do:

val arr = arrayOfNulls<Array<String?>>(5)

This gives you a Array<Array<String?>?>. I would imagine having the inner array being nullable can be quite inconvenient sometimes.

If you just want a n by m array, but want the elements null by default, you can do:

val arr = Array(5) { arrayOfNulls<String>(10) }

This roughly translates to this in C#:

var arr = new string[5, 10];

Upvotes: 3

Related Questions