简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM