0

I need to extend List to be able to overload [] operator.

I tried all the approaches from here: How do I extend a List in Dart?. But all of them give me the same error A value of type 'List<dynamic>' can't be assigned to a variable of type 'MyCustomList<int>'. when I assign usual List to my extended CustomList:

import 'package:quiver/collection.dart';

class MyCustomList<E> extends DelegatingList<E> {
  final List<E> _l = [];
  List<E> get delegate => _l;
}

void main() {
  MyCustomList<int> l = []; // << error here
}

Is it possible to extend so that this error disappeared?

I know that I can change to:

MyCustomList<int> l = [] as MyCustomList<int>;

But I would like to avoid it because of it would require massive changes in my real code.

Andrey
  • 5,932
  • 3
  • 17
  • 35
  • Even the casting solution will not work, because you're trying to cast an instance of a superclass to a subclass. The literal `[]` always creates an instance of `List`, which has no member `delegate`, and therefore cannot be casted to `MyCustomList` – Michael Horn Apr 02 '23 at 14:35

1 Answers1

1

The issue with your code is that you're trying to assign a List<int> to a variable of type MyCustomList<int>.

You can create a constructor and initialize the private list _l.

class MyCustomList<E> extends DelegatingList<E> {
  MyCustomList(List<E> list) {
    _l.addAll(list);
  }

  final List<E> _l = [];

  List<E> get delegate => _l;
}

void main() {
  MyCustomList<int> l = MyCustomList([1, 2, 3]);
}

Note: seems the [] operator overload is for accessing and assigning value to an element and you can't use it for instantiate list.

@override
void operator []=(int index, E value) => _l[index] = value;

@override
E operator [](int index) => _l[index];
Hamed
  • 5,867
  • 4
  • 32
  • 56