Ask Your Question
0

Is it impossible to assign a `List` to a List that has been extended in Dart?

asked 2023-07-17 03:48:16 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-17 03:53:02 +0000

qstack gravatar image

No, it is not impossible to assign a List to a list that has been extended in Dart. However, it depends on the type of extension that has been made. If the extension adds additional methods or properties to the existing List type, then you can assign a regular List to the extended list type. For example:

extension CustomList<T> on List<T> {
  void customMethod() {
    // custom implementation
  }
}

void main() {
  List<int> regularList = [1, 2, 3];
  List<int> extendedList = regularList;
  extendedList.customMethod(); // this works because `customMethod` is part of the extension
}

However, if the extension overrides any of the existing methods or properties of the List type, then assigning a regular List to the extended list type can result in unexpected behavior. For example:

extension CustomList<T> on List<T> {
  int get length => -1; // override the `length` property
}

void main() {
  List<int> regularList = [1, 2, 3];
  List<int> extendedList = regularList;
  print(extendedList.length); // this will print -1, not 3
}

In this case, it is generally safer to create a new instance of the extended list type and copy the elements from the original list to the new list. For example:

extension CustomList<T> on List<T> {
  List<T> copy() {
    return List<T>.from(this);
  }
}

void main() {
  List<int> regularList = [1, 2, 3];
  List<int> extendedList = regularList.copy();
  // now `extendedList` is a copy of `regularList` with the `CustomList` extension applied
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-17 03:48:16 +0000

Seen: 12 times

Last updated: Jul 17 '23