Search code examples
scalaconcurrencyfunctional-programmingimmutabilitymutable

Mutable reference to immutable data


I often time hear the term "Mutable reference to immutable data". In my case this was for Scala. If you have a mutable reference, wouldn't this imply that the immutable data is mutable? I am having hard time understanding the theory and practical aspect of it. Example would be great.


Solution

  • It means you can mutate the reference (change what it refers to) but not mutate the data (change what's behind the reference). The difference matters as soon as there are multiple references to the data, which happens all the time in a language like Scala (assignment, parameter passing, adding to collections, etc.). For example:

    var x = List(1);
    var y = x;
    x = List(2);
    // y.head == 1
    // x.head == 2
    

    Note that this distinction applies even to Java:

    String x = "foo";
    String y = x;
    x = "bar";
    // y.equals("foo")
    // x.equals("bar")
    

    Note that in both examples, we mutated the references x and y, but we didn't (and in fact couldn't) mutate the objects they refer to.