Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

139
Vistas
Multidimensional array of Objects in 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!

9 months ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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)
            }
         }
9 months ago · Santiago Trujillo Denunciar

0

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

9 months ago · Santiago Trujillo Denunciar

0

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()
9 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos