Home > Mobile >  How do I initialize a nxm List<List<String>> matrix in Kotlin
How do I initialize a nxm List<List<String>> matrix in Kotlin

Time:11-14

new bee in Kotlin here, apologize for the simple question but how do I initialize a matrix of strings? I need this:

val board: List<List<String>>

I looked at this sample for integers and did the following:

val row = 4
val col = 3
var matrix: Array<IntArray> = Array(row) { IntArray(col) }

Then I tried to replace Int by String but it won't build:

val board: List<List<String>> = Array(row) { StringArray(col) }

thank you.

CodePudding user response:

If you're trying to initialize a 2D String array you can do it like this:

fun main() {
    val height = 5
    val width = 5
    val stringArray = Array(height) { Array(width) {""} }
}

no need to make board of type List<List<String>>.

To test the code, we can initialize the array instead with any character and print it out:

fun main() {
    val height = 5
    val width = 5
    val stringArray = Array(height) { Array(width) {"a"} }
    for (i in stringArray) {
        for (j in i) {
            print(j)
        }
        println()
    }
}

which results in:

aaaaa
aaaaa
aaaaa
aaaaa
aaaaa
  • Related