Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 419
Mohamed Hayibor Avatar asked Dec 13 '16 13:12

Mohamed Hayibor


1 Answers

You can wrap an array in an UnmodifiableListView from dart:collection and pass this around instead of the array itself. I think this is the most basic buit-in way.

like image 176
Günter Zöchbauer Avatar answered Sep 22 '22 23:09

Günter Zöchbauer