putIfAbsent method

IMap<K, V> putIfAbsent(
  1. K key,
  2. V ifAbsent(), {
  3. Output<V>? previousValue,
})

Look up the value of key, or add a new value if it isn't there.

Returns the modified map, and sets the previousValue associated to key, if there is one. Otherwise calls ifAbsent to get a new value, associates key to that value, and then sets the new previousValue.

IMap<String, int> scores = {"Bob": 36}.lock;

Item<int> item = Item();
for (String key in ["Bob", "Rohan", "Sophia"]) {
  item = Item();
  scores = scores.putIfAbsent(key, () => key.length, value: item);
  print(value);    // 36, 5, 6
}

scores["Bob"];     // 36
scores["Rohan"];   //  5
scores["Sophia"];  //  6

Calling ifAbsent must not add or remove keys from the map.

Implementation

IMap<K, V> putIfAbsent(
  K key,
  V Function() ifAbsent, {
  Output<V>? previousValue,
}) {
  // Is present.
  V? value = this[key];
  if ((value != null) || containsKey(key)) {
    previousValue?.save(value);
    return this;
  }
  //
  // Is absent.
  else {
    var calculatedValue = ifAbsent();
    previousValue?.save(calculatedValue);
    Map<K, V> map = ListMap.fromEntries(
      entries.followedBy([MapEntry(key, calculatedValue)]),
      sort: config.sort,
    );
    return IMap._unsafeFromMap(map, config: config);
  }
}