Skip to content

Add List.getOrNull() #627

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
windrunner414 opened this issue Sep 17, 2021 · 2 comments
Closed

Add List.getOrNull() #627

windrunner414 opened this issue Sep 17, 2021 · 2 comments

Comments

@windrunner414
Copy link
Contributor

add a extension function getOrNull(int index) on List to get element at the specified index safely. If out of bounds, return null.
It can work well with nnbd.

ref: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/get-or-null.html

@alexeyinkin
Copy link

This should be on Iterable since elementAt is there. Also it might be named elementAtOrNull for consistency.

@mosuem mosuem transferred this issue from dart-archive/collection Oct 21, 2024
@lrhn
Copy link
Member

lrhn commented Nov 24, 2024

No current plans to treat index errors as acceptable in lists. Don't expect that to change. It's very easy to do a list.length check first, rather than have a function that silently ignores out-of-bound accesses.

For iterable, it makes more sense ... but annoyingly an operation on iterable will work for List too.
Still, I'd prefer something cleaner, not null based, like Option<T> tryElementAt(int index) that would return a recognizable non-value if index is too big. (And it'll still throw for negative indices.)

@lrhn lrhn closed this as not planned Won't fix, can't repro, duplicate, stale Jan 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants