In editor hint you get:
scores.putIfAbsent(key, () => numValue);
I am adding single "rows" to my Maps with commands:
myMap.putIfAbsent(9, () => 'Planned');
yourMap.putIfAbsent('foo', () => true);
so: what does that () mean ?
The putIfAbsent
function takes two arguments, the key and a function that will return the new value, if needed.
See https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-core.Map#id_putIfAbsent
The reason for the second argument to be a function returning the new value, and just not the value itself, is that if the map already contains the key, it's sometimes undesirable to create the value.
Consider the following example:
var map = ...;
var key = ...;
map.putIfAbsent(key, new Value());
If map
already contains key
, the new value object is not used at all. If the Value object is some heavy or expensive to allocate object, this is an unwanted side-effect.
By taking a function instead
var map = ...;
var key = ...;
map.putIfAbsent(key, () => new Value());
It will only execute the function if the key
is not present in map
, and the value is needed.
So, to answer the syntax question. A expression of the form () => ...
is a short hand of a function expression, returning the result of the first expression. A small example:
var function = () => "some string";
var str = function();
print(str);
will print "some string".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With