Home > Software engineering >  Kotlin. How can I get to an individual item of a 2d array?
Kotlin. How can I get to an individual item of a 2d array?

Time:11-14

I am creating a GameOfLife project (https://en.wikipedia.org/wiki/Conway's_Game_of_Life) and for that I have decided that I require 2d array. But I cannot find a simple way to access it's elements like in java where you can go array[index][index]. How can I access individual elements?

val board = Board(
    arrayOf(
        arrayOf(2, 2, 2),
        arrayOf(2, 2, 2),
        arrayOf(2, 2, 2)
    )
)
println(board.board[2][2]) // this doesn't work

I tried to access it like in Java because Kotlin is derived from it but I guess that is wrong. I can't find an simple answer to that answer in Google. I am a beginner so please don't be angry with me if that is something obvious, because for me it isn't and I want to learn :). Maybe I shouldn't create 2 arrays like that?

CodePudding user response:

The some2dArray[index][index] syntax works fine in Kotlin. In your example you are creating a Board object and passing a 2d array into it but you don't show how you declare the Board class. If you just create a 2d array you can see that the indexing works.

fun main(args: Array<String>) {
  val board = 
    arrayOf(
        arrayOf(2, 2, 2),
        arrayOf(2, 2, 2),
        arrayOf(2, 2, 2)
    )

  println(board[2][2]) // this works
}

If you declare your Board class as having a 2d array called board, what you have will also work.

class Board(val board: Array<Array<Int>>)

fun main(args: Array<String>) {
  
  val board = Board(arrayOf(
        arrayOf(2, 2, 2),
        arrayOf(2, 2, 2),
        arrayOf(2, 2, 2)
  ))

 println(board.board[2][2]) // this also works
}
  • Related