Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin 2d Array initialization

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?

like image 849
Khufu Avatar asked Jul 19 '17 19:07

Khufu


2 Answers

You can make worldTiles a lateinit property, and do all the initialization in the generate function:

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

  lateinit var worldTiles: Array<Array<WorldTile>>

  fun generate() {
    worldTiles = Array(size_x, {
        Array(size_y, {
            WorldTile()
        })
    })
  }
}

If you try to access worldTiles before calling generate you will get an exception warning that it hasn't been initialized yet.

like image 145
Pixel Elephant Avatar answered Nov 11 '22 03:11

Pixel Elephant


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.
    }
}
like image 33
A-Sharabiani Avatar answered Nov 11 '22 02:11

A-Sharabiani