Search code examples
objectdartimmutabilitymutation

What are the ways to avoid object mutation in Dart-lang?


If we take the following snippet as an example:

main() {
    List<int> array = [1, 2, 3, 4];
    List<int> newArray = change(array);

    print(array); // [99, 2, 3, 4]
    print(newArray); // [99, 2, 3, 4]
    print(newArray == array); // true
}

change(List<int> array) {
    var newArray = array;
    newArray[0] = 99;
    return newArray;
}

The original array gets mutated. I was expecting that by passing the array (object) to the change function and assigning a new variable to it that I could avoid mutation. I am aware that the built_collection library seems like the main go-to for immutable collections. Is there any native way the core library that would allow for a deep freeze or prevent side effects (operations inside another function)?


Solution

  • Objects are passed by reference. This is by design: objects are often large data structures and internally making a copy every time an object is passed to a function can be very inefficient. (This is the same approach as that used by other major object oriented languages.)

    As a result, array and newArray are two names for the same underlying List in your code.

    If you want to explicitly create a new list, just change

    var newArray = array;
    

    to:

    var newArray = new List.from(array);