Kotlin function parameter: Val cannot be reassigned

前端 未结 3 1469
一生所求
一生所求 2020-12-03 13:26

I have written Red–black tree in Kotlin. Fun insertFixup restores balance after inserting new element (z: Node? is new element). Algorithm of tree balancin

3条回答
  •  北海茫月
    2020-12-03 14:18

    Function parameters in Kotlin are basically read-only val's inside the function, so z here will always refer to the original object that was passed in.

    If you need to modify what it points to while your function is running, you'll have to make a local copy of it at the beginning of the function, and then you can make that a var.

    For example, you could start your function like this, which lets you reassign this local var later:

    fun insertFixup(_z: Node?) {
        var z = _z
        // ...
        z = z.parent
        // ...
    }
    

提交回复
热议问题