Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart Map syntax: putIfAbsent('FirstKey',() => 1); What is: ()?

Tags:

dart

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 ?

like image 550
heiklap Avatar asked Aug 10 '14 09:08

heiklap


1 Answers

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".

like image 118
Anders Johnsen Avatar answered Oct 20 '22 23:10

Anders Johnsen