Map over nullability #48214
Labels
area-core-library
SDK core library issues (core, async, ...); use area-vm or area-web for platform specific libraries.
library-core
type-enhancement
A request for a change that isn't a bug
Hi all, it's my first first time opening an issue so I hope it goes well 👋
I'm not sure if this is the right place, because it's less of a new language feature and more of an improvement of the standard library.
The problem:
?.
only supports methods (including extension methods)For example, indexing into a
Map<K, V>
returns aV?
.We can always add an extension on
V
to have a nicem[key]?.foo()
, but adding a lot of extensions just to enjoy?.
is inelegant and there's surely a better solution.The proposed solution: a
MappableNullable
extensionConsider the following:
This is a slightly more useful version of
?.
:I'm proposing this addition to the standard library because it's applicable pretty much anywhere nullables are involved.
For instance, Kotlin has a few similar helpers. Especially,
let
can trivially be used asmapNullable
.Addendum:
Going a step further, here are a few more extensions that I'd be happy to have in the standard library.
These are useful abstractions, but arguably less widely applicable, being tailored to a very functional style.
Related:
List.elementAt
throws on failure, but potentially this can be achieved withlist[noSuchIndex].orElse(fallback)
orElse
s, the aboveWithDefault
approach handles all cases (assuming the related functions return nullable results instead of throwing, otherwise a slightly different abstraction is needed).The text was updated successfully, but these errors were encountered: