Home > Enterprise >  Why this dart function change the value of the variable matches?
Why this dart function change the value of the variable matches?

Time:06-14

I can't understand this:

//Globals variables
List<int> results = [1,1];
List<List<int>> matches = [[1,3],[2,4]];

void main() {
  print("before");
  print(matches); //output: [[1,3],[2,4]]
  List<int> losers = getEliminatedPlayer(matches);
  print("after");
  print(matches); //output: [[3],[4]]
}

List<int> getEliminatedPlayer(List<List<int>> matches) {
  List<List<int>> losers = matches;

  for (var i = 0; i < losers.length; i  ) {
    losers[i].remove(losers[i][results[i] - 1]);
  }

  var flattened = losers.expand((loser) => loser).toList();

  print(flattened);
  return flattened;
}

Why even if i don't work on the matches variable it changes? How can I avoid it?

CodePudding user response:

List losers = matches does not make a copy of the matches list but merely gives it an additional variable that points to the exact same list. So changes made to either variable will be reflected in both. To solve you need to make a deep copy of it. In your case you could do this:

List getEliminatedPlayer(List matches) {
  List losers = matches.map((e) => e.toList()).toList();
  for (var i = 0; i < losers.length; i  ) {
  losers[i].remove(losers[i][results[i] - 1]);
  }   
  var flattened = losers.expand((loser) => loser).toList();
  print(flattened);
  return flattened;
}
  • Related