1 | initial version |
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
}