Kotlin 如何创建可变列表<;可变列表<;Int>&燃气轮机;来自可变列表<;可变列表<;布尔值>&燃气轮机;在科特林也有同样的尺寸

Kotlin 如何创建可变列表<;可变列表<;Int>&燃气轮机;来自可变列表<;可变列表<;布尔值>&燃气轮机;在科特林也有同样的尺寸,kotlin,Kotlin,我想知道如何创建一个与给定的matrix=MutableList大小相同的newmatrix=MutableList。我特别希望newmatrix为零,这可以通过循环实现。 第一个想法是这样做: var newmatrix = matrix // tworzymy macierz równą zero for (k in 0..matrix.indices.last) { for (l in 0..matrix[0].indices.last) { newmatrix[k

我想知道如何创建一个与给定的
matrix=MutableList
大小相同的
newmatrix=MutableList
。我特别希望
newmatrix
为零,这可以通过循环实现。
第一个想法是这样做:

var newmatrix = matrix
// tworzymy macierz równą zero
for (k in 0..matrix.indices.last) {
    for (l in 0..matrix[0].indices.last) {
        newmatrix[k][l] = 0
    }
}

但是它当然不起作用,因为它说
newmatrix
具有类型
Boolean
,而不是
Int

您可以编写一个扩展函数,将
可变列表
转换为
可变列表
,然后在列表上使用
forEach
,以转换每个项目:

// extension function for an Int-representation of a Boolean-list
fun MutableList<Boolean>.toIntList(): MutableList<Int> {
    var result: MutableList<Int> = mutableListOf()
    this.forEach { it -> if (it) { result.add(1) } else { result.add(0) } }
    return result
}

fun main(args: Array<String>) {
    // example Boolean-matrix
    var matrix: MutableList<MutableList<Boolean>> = mutableListOf(
            mutableListOf(true, true, true),
            mutableListOf(false, false, false),
            mutableListOf(false, true, false),
            mutableListOf(true, false, true)
    )
    // provide the structure for the result
    val newMatrix: MutableList<MutableList<Int>> = mutableListOf()
    // for each Boolean-list in the source list add the result of toIntList() to the result
    matrix.forEach { it -> newMatrix.add(it.toIntList()) }
    // print the source list
    println(matrix)
    // print the resulting Int list
    println(newMatrix)
}
可能有不同甚至更好的转换方法,但这似乎足够了