Search code examples
kotlindo-whilemutablemap

Kotlin: Why does val b (Map) change over the iteration even though actions occur over another var a in do-while loop?


Why does such code only occur in one iteration? Why does "b" change simultaneously with "a" after assignment before the end of the iteration?

I made a similar code where (a) and (b) are integers, then (b) does not change until the next iteration. Why does it behave differently with Map?

var a = mutableMapOf("z" to 1)

do {
    val b = a
    a["x"] = 2
    // why here b == a in the first iteration?
} while (a != b)

Solution

  • According to @jsamol comment, it says: "Similar to Java, Kotlin never implicitly copies objects on assignment. Variables always hold references to objects, and assigning an expression to a variable only copies a reference to the object, not the object itself."

    I've changed the condition so I can compare integers, not maps. How it works.

    var a = mutableMapOf("z" to 1)
    
    do {
        val b = a.size
        a["x"] = 2
    } while (a.size != b)