Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional array of Objects in Kotlin

Tags:

arrays

oop

kotlin

I'm new in Kotlin, and I want to create a multi dimensional array of a custom class, with null permitted. Something like that

private var array_map = arrayOf<Array<Obstacle?>>()

...

array_map[1][2] = Obstacle()

How can I do it? Thank you!

like image 270
Carlos Vázquez Avatar asked Mar 12 '19 16:03

Carlos Vázquez


3 Answers

In case you need the index of each element in the constructor of the elements of the array:

Declaration:

var matrix: Array<Array<Obstacle?>>

Instantiation and initialization:

matrix = Array(numRows) { row ->
            Array(numCols) { col ->
                Obstacle(row, col)
            }
         }
like image 184
Victor Alonso Barberan Avatar answered Oct 12 '22 17:10

Victor Alonso Barberan


You can use private var arrayMap: Array<Array<Obstacle?>> = arrayOf(). Just wrap with as much Array<> as you need.

like image 34
nyarian Avatar answered Oct 12 '22 17:10

nyarian


Not sure if this is what you want, but imagine that Obstacle is a custom class with a field num as below

data class Obstacle(var num: Int){}

A 2D array of the Obstacle object would be as below:

val array: Array<Obstacle?> = arrayOf(Obstacle(123), Obstacle(234))
val arrayOfArray: Array<Array<Obstacle?>> = arrayOf(array)
println(arrayOfArray[0][0]) // would print Obstacle(num=123)
println(arrayOfArray[0][1]) // would print Obstacle(num=234)

So you should be declaring your 2D array as below

val arrayOfArray: Array<Array<Obstacle?>> = arrayOf()
like image 36
Madhu Bhat Avatar answered Oct 12 '22 15:10

Madhu Bhat