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?
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?
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"]);
}