Spec-Zone.ru › Dart 2

dart:collection

Метод putIfAbsent

V putIfAbsent(
  1. K key,
  2. V ifAbsent( )
)
override

Получить значение key, или добавить новую запись, если её нет.

Возвращает значение, связанное с key, если оно есть. В противном случае вызывает ifAbsent, чтобы получить новое значение, связывает key с этим значением и затем возвращает новое значение.

final diameters = <num, String>{1.0: 'Earth'};
final otherDiameters = <double, String>{0.383: 'Mercury', 0.949: 'Venus'};

for (final item in otherDiameters.entries) {
  diameters.putIfAbsent(item.key, () => item.value);
}
print(diameters); // {1.0: Earth, 0.383: Mercury, 0.949: Venus}

// If the key already exists, the current value is returned.
final result = diameters.putIfAbsent(0.383, () => 'Random');
print(result); // Mercury
print(diameters); // {1.0: Earth, 0.383: Mercury, 0.949: Venus}

Вызов ifAbsent не должен добавлять или удалять ключи из карты.

Реализация

V putIfAbsent(K key, V ifAbsent()) {
  int comp = _splay(key);
  if (comp == 0) {
    return _root!.value;
  }
  int modificationCount = _modificationCount;
  int splayCount = _splayCount;
  V value = ifAbsent();
  if (modificationCount != _modificationCount) {
    throw ConcurrentModificationError(this);
  }
  if (splayCount != _splayCount) {
    comp = _splay(key);
    // Key is still not there, otherwise _modificationCount would be changed.
    assert(comp != 0);
  }
  _addNewRoot(_SplayTreeMapNode(key, value), comp);
  return value;
}

© 2012 the Dart project authors
Licensed under the BSD 3-Clause "New" or "Revised" License.
https://api.dart.dev/stable/2.18.5/dart-collection/SplayTreeMap/putIfAbsent.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API