List <T> Class Extension
Is it possible to expand the general list with my own specific list. Sort of:
class Tweets<Tweet> extends List<T> And what would the constructor look like if I wanted to build using my own constructor:
Datasource datasource = new Datasource('http://search.twitter.com/search.json'); Tweets tweets = new Tweets<Tweet>(datasource); And how to call the parent constructor then, since it is not executed in the extended class?
+6
2 answers
Here is what I learned to expand the list behavior:
- import 'dart: collection';
- extends ListBase
- implement [] and getter and setter.
See the example figure below. It uses its own Tweets method and standard list.
Note that add / addAll is deleted.
Conclusion:
[hello, world, hello] [hello, hello] [hello, hello] code:
import 'dart:collection'; class Tweet { String message; Tweet(this.message); String toString() => message; } class Tweets<Tweet> extends ListBase<Tweet> { List<Tweet> _list; Tweets() : _list = new List(); void set length(int l) { this._list.length=l; } int get length => _list.length; Tweet operator [](int index) => _list[index]; void operator []=(int index, Tweet value) { _list[index]=value; } Iterable<Tweet> myFilter(text) => _list.where( (Tweet e) => e.message.contains(text)); } main() { var t = new Tweet('hello'); var t2 = new Tweet('world'); var tl = new Tweets(); tl.addAll([t, t2]); tl.add(t); print(tl); print(tl.myFilter('hello').toList()); print(tl.where( (Tweet e) => e.message.contains('hello')).toList()); } +4
Dart List is an abstract class with factories.
I think you could implement it like this:
class Tweet { String message; Tweet(this.message); } class Tweets<Tweet> implements List<Tweet> { List<Tweet> _list; Tweets() : _list = new List<Tweet>(); add(Tweet t) => _list.add(t); addAll(Collection<Tweet> tweets) => _list.addAll(tweets); String toString() => _list.toString(); } main() { var t = new Tweet('hey'); var t2 = new Tweet('hey'); var tl = new Tweets(); tl.addAll([t, t2]); print(tl); } There seems to be no direct way to do this, and it looks just like the big code: http://code.google.com/p/dart/issues/detail?id=2600
Update:. One way is to use noSuchMethod() and call forwarding.
+1