aDictionary at: 12 ifAbsent: ['default'].
Dart has operators you can define as messsages, so their default syntax would be
aMap[12]='something';
But that's not the same operation, as it doesn't have the ability to say what to do if the key is missing. It does define
aMap.putIfAbsent(12,'default');
but that's not the same as at:ifAbsent:, both because it always adds something to the map/dictionary, and because the thing you're adding is a value, not the result of evaluating a block.
However, Dart also has named keyword arguments to methods. They're not shown, as far as I saw, in the introductory materials on the site, and I didn't notice them in the sample code that I looked at, but they're in the spec. The form is
at(var key, [ifAbsent]) {
if (containsKey(key)) return this[key];
if (ifAbsent is Function)
return ifAbsent();
else
return ifAbsent;
}
and to invoke it we'd do something like
Map aMap = { "one": 1, "two":2};
aMap.at("one",ifAbsent: "default");
or, if we felt like formatting it slightly differently, it seems that there can be whitespace between the dot and the method, so
aMap.
at("one",
ifAbsent: "default"
or aMap.
at: 'one',
ifAbsent: ()=> throw SomeException;
Both of those latter forms, while they have some additional bits of punctuation, look interestingly like syntax I'm more used to. Named parameters can also have default values, which could also be useful, though I tried
someFunction(var a, [b= (var x)=>x * 2])
and while it didn't complain of a syntax error, variable b was null if not specified. That might just be a compiler bug, or it may be that a closure literal isn't allowed there, I'm not sure.
I haven't tried using these on any kind of scale to see how usable they would be in practice, and they obviously aren't the preferred style in the examples, but I found it interesting. And as a minor point, it's odd that for normal parameters I have to specify either a type or "var" but that doesn't seem to be necessary for the named parameters.
No comments:
Post a Comment