Add getOrDefault method to Listing and Mapping (#1053)

This PR adds methods to Listing and Mapping that can be used to retrieve members. If the member for the index/key isn't present, it applies default to the index/key. In both cases, this is essentially sugar for getOrNull(<index/key>) ?? default.apply(<index/key>).

Co-authored-by: Daniel Chao <daniel.h.chao@gmail.com>
This commit is contained in:
Jen Basch
2025-07-22 15:45:49 -07:00
committed by GitHub
parent 306a3b0fc2
commit 85e4f133a4
7 changed files with 65 additions and 2 deletions

View File

@@ -1887,6 +1887,14 @@ class Listing<out Element> extends Object {
@Since { version = "0.27.0" }
external function getOrNull(index: Int): Element?
/// Returns the element at [index].
///
/// Returns [default] applied to [index] if [index] is outside the bounds of this listing.
///
/// This is equivalent to `getOrNull(index) ?? default.apply(index)`.
@Since { version = "0.29.0" }
external function getOrDefault(index: Int): Element
/// Tells if this listing has no duplicate elements.
///
/// Facts:
@@ -2050,6 +2058,13 @@ class Mapping<out Key, out Value> extends Object {
/// This is the nullable equivalent of the subscript operator (`object[key]`).
external function getOrNull(key: Any): Value?
/// Returns the value associated with [key] or [default] applied to [key] if this mapping does
/// not contain [key].
///
/// This is equivalent to `getOrNull(key) ?? default.apply(key)`.
@Since { version = "0.29.0" }
external function getOrDefault(key: Any): Value
/// Folds the entries of this mapping in iteration order using [operator], starting with [initial].
external function fold<Result>(initial: Result, operator: (Result, Key, Value) -> Result): Result