Kotlin 2d Array initialization

Viewed 15263

Please take a look at my 2D-Array-Initialization. The code works.

class World(val size_x: Int = 256, val size_y: Int = 256) {

  var worldTiles = Array(size_x, { Array(size_y, { WorldTile() }) })

    fun generate() {
      for( x in 0..size_x-1 ) {
          for( y in 0..size_y-1 ) {
              worldTiles[x][y] = WorldTile()
          }
      }
  }
}

The problem is that it runs the initialization twice. Basically I want to instantiate the WorldTile-Object in the generate() function. So Line 3 shouldn't call "new WorldTile" there. How can I do that?

Also is that the proper Kotlin way of traversing a 2d-Array?

4 Answers

To initialise all to a fixed value:

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

To initialise with a lambda:

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

Another way: Here is an example of initialising a 2D array of Float numbers (3 by 6):

var a = Array(3) { FloatArray(6)} // define an 3x6 array of float numbers
for(i:Int in 0 until a.size) {
    for(j : Int in 0 until a[i].size) {
        a[i][j] = 0f // initialize with your value here.
    }
}
val twoDimStringArray= arrayOf(
    arrayOf("first","second"),
    arrayOf("foo"),
    arrayOf("bar","great kotlin")
)
for (i in twoDimStringArray){
    for(j in i){
        println(j)
    }
}

first
second
foo
bar
great kotlin

A bit late but could help to somebody if is working with strings

//init 2d array with a fixed size: 
 var data2 = Array<Array<String>>(2) { arrayOf()}
// fill the 2d array
        data2[0] = arrayOf("123","Freddy x","27")
        data2[1] = arrayOf("124","Elon y","45")

cheers!

Related