-1

I am genuinely shocked on how hard it is to find a good explanation on how to create a 2d array in Kotlin for an object.

These are my attempts from what I have found neither here on stack and online neither work, why? how do I create a 2d array of objects not built into Kotlin!!!

var matrix : Array<Array<myObject?>> = null

//var arr2D = Array(10) { Array(10) { myObject(this) } }

for (i in 0 until 9) {
        for (j in 0 until 9) {
            matrix[i][j] = myObject(this)
        }
    }

It says "null can not be a value of a non-null type" so I guess I have to use an arrayofnulls(), but cannot find a source can someone help me or give me a source?

francisRH
  • 13
  • 3

1 Answers1

1

This is how you create a 2D Array in Kotlin with a user made object. ArrayofNulls allows you to set all indexes in the array to null and then just initialize them later with a for loop!

    val matrix = Array(10) {
        arrayOfNulls<myObject?>(
            10
        )
    }
francisRH
  • 13
  • 3
  • 2
    Guess what, you don't even need a for loop if you are going to initialize the array, just write `val matrix : Array> = Array(10){ Array(10){ MyObject() } }` . In case the initialization of the elements depends on the array indices, you can write `val matrix : Array> = Array(10){ i -> Array(10){ j -> MyObject(i,j) } }` – Ricky Mo Nov 24 '21 at 01:30
  • Thanks, I am right in thinking that this will create a 10x10 matrix? – francisRH Nov 24 '21 at 11:08
  • @francisRH Well, yes and no. Kotlin does not have multidimensional arrays or matrices. This code creates an array of 10 arrays and each inner array has size of 10. So yes, this is similar to 10x10 matrix, but speaking precisely it is not a 2d array, but array of arrays. – broot Nov 24 '21 at 11:15