How does one make a Dart object/class indexable?

2019-07-20 03:16发布

问题:

In Python I can make any class support indexing by overriding __getitem__ like so:

class Test:
   def __getitem__(self, key):
      return self.data[key]

Does Dart have a similar construct for this?

回答1:

Assuming that the __getitem__ thing lets you use the "indexing" syntax (object[index]), yes, Dart lets you do the same by defining operator []. Example:

class Test {
  var data = {
    "a": 1,
    "b": 2
  };

  operator [](index) => data[index];
}

main() {
  var t = new Test();
  print(t["a"]);
  print(t["b"]);
}

You can also define the "opposite" operator []=:

class Test {
  Map data = {
    "a": 1,
    "b": 2
  };

  operator [](index) => data[index];
  operator []=(index, value) { data[index] = value; }
}

main() {
  var t = new Test();
  print(t["a"]);
  print(t["b"]);
  t["c"] = 3;
  print(t["c"]);
}