Why `List<Long<Long>>` cannot 2-dim index set?

Code:

fun read() : List<Long> {
    return readLine()!!.split(' ').map { it.toLong() }
}
class Matrix constructor(a: Long, b: Long, c: Long, d: Long) {
    var A : List<List<Long>> = listOf(listOf(0L, 0L), listOf(0L, 0L))
        get() = field
        set(value) {A = value}
    init {A = listOf(listOf(a, b), listOf(c, d))}
    constructor(Ap: List<List<Long>>) : this(Ap[0][0], Ap[0][1], Ap[1][0], Ap[1][1]) {
    }
    fun Mult(other: Matrix) : Matrix {
        var ret: List<List<Long>> = listOf(listOf(0L, 0L), listOf(0L, 0L))
        for (i in 0 until 2)
            for (j in 0 until 2)
                for (k in 0 until 2)
                    ret[i][j] = ret[i][j] + (A[i][k] * other.A[k][j])
        return Matrix(ret)

    }
}
const val M = 998244353
fun main(args: Array<String>) {
}

so, we got two errors: Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public inline operator fun kotlin.text.StringBuilder /* = java.lang.StringBuilder */.set(index: Int, value: Char): Unit defined in kotlin.text, and Kotlin: No set method providing array access.

but ret[i][j], A[i][j], other.A[i][j] is all in type Long!

Why?

List is immutable in Kotlin, therefore elements of it cannot be set.

If you need a mutable list, you can use the type MutabeList, e.g.

var ret: MutableList<MutableList<Long>>
    = mutableListOf(mutableListOf(0L, 0L), mutableListOf(0L, 0L))

thanks

Of course tlin47’s answer is correct, however it might be also instructive to show how the code could be rewritten without using mutable lists:

fun Mult(other: Matrix): Matrix {
    val ret =
        (0 until 2).map { i ->
            (0 until 2).map { j ->
                (0 until 2).map { k ->
                   A[i][k] * other.A[k][j]
                }.sum()
            }.toList()
        }.toList()
    return Matrix(ret)
}
1 Like