Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart String Iterable interface

Why doesn't Dart String class implement the iterable interface? It seems like there is an obvious notion of iteration for strings, i.e. just return each character in turn.

like image 220
David K. Avatar asked Feb 12 '23 05:02

David K.


2 Answers

Maybe not that terse as you would like

String s = 'foo';
s.codeUnits.forEach((f) => print(new String.fromCharCode(f)));
s.runes.forEach((f) => print(new String.fromCharCode(f)));
like image 113
Günter Zöchbauer Avatar answered Mar 29 '23 16:03

Günter Zöchbauer


To answer the "Why":

The Iterable interface is a fairly heavy-weight interface (many members) that is intended for collections of elements.

While a String can be seen as a List of characters (but Dart doesn't have a type for characters, so it would really be "List of single-character Strings"), that is not its main usage, and also being an Iterable would clutter the actual String methods.

A better solution would be to have a List view of a String. That is fairly easily doable:

class StringListView extends ListBase<String> {
  final String _string;
  StringListView(this._string);

  @override
  String operator [](int index) => _string[index];

  @override
  int get length => _string.length;

  @override
  set length(int newLength) {
    throw UnsupportedError("Unmodifiable");
  }

  @override
  void operator []=(int index, String v) {
    throw UnsupportedError("Unmodifiable");
  }
}

Would be even easier if the libraries exposed the UnmodifiableListBase used to make UnmodifiableListView.

like image 42
lrn Avatar answered Mar 29 '23 16:03

lrn