Multi-dimensonal arrays are a pain point in Kotlin

I love so much about Kotlin, but I have found one area where Java is actually friendlier to work with: mutli-dimensional arrays.

Not just in terms of verbosity, but I Think the readability is better in Java.

example:

Java:
int points = new int[10][10];

Kotlin:
val points = Array<Array<Int>>()

at two dimensionals it is managable, but at three or four I think it would be quite ugly.

Or is it possible I have missed a better way to do this?

5 Likes

Could you share your use cases

The simplest use case is a 2d array to represent a grid for a tile based game.

It is not a big deal, but everything else about Kotlin is so nice this jumps out at me.

Ok, thanks

Have you considered adding Ceylon style type aliases? Would solve this problem.

Yes, we are planning to support something like this

1 Like

I think, this works. I have tried it in a Scratch file:

val d2 = arrayOf( Array(255,{i → i-1+1}), Array(255,{i → i-1+1}) )

d2[0][1]

And i think, it is no problem to make 3 dimensional Arrays.

You should track this issue: https://youtrack.jetbrains.com/issue/KT-21670. Multi-dimensional arrays are not that simple. Java arrays are quite easy to use, but are not what you need in terms of performance. Lightweight 2-dim array builders are quite easy to add in you project like this:

typealias DoubleArray2D = Array<DoubleArray>
fun doubleArray2D(rows: Int, cols: Int, block: (i: Int, j: Int) -> Double): DoubleArray2D{
  return Array(rows){ i ->
      DoubleArray(cols){ j ->
          block(i,j)
      }
  }
}
1 Like