dart-lang / collection

The collection package for Dart contains a number of separate libraries with utility functions and classes that makes working with collections easier.

Home Page:https://pub.dev/packages/collection

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add `List.get()` method

Noah765 opened this issue · comments

Handling range errors is a common task and can be quite annoying. If there was a List.get() function like in other languages (e.g. Rust), a lot of code could be simplified. I think that it is even worth adding this to the dart standard library.

This is one possible implementation:

extension ListGet<E> on List<E> {
  E? get(int index) {
    if (index < 0 || index > length - 1) return null;
    return this[index];
  }
}

Example code that would be simplified:

if (startingIndex > 0) {
  if (list[startingIndex] case '|' || '7' || 'F') print('match');
}

could turn into

if (list.get(startingIndex) case '|' || '7' || 'F') print('match');

I don't expect to add such "allow invalid indices" methods to the platform libraries or to this package.
They can to easily hide an actual error behind a null value.

Generally, such operations are only made available when checking whether the argument is valid is non-trivial, or it's about as expensive as doing the operation.

Here, having a negative value for something that might be a list index suggests that the value needs validation, or is being used for something or it wasn't intended for.

If you want such a member for your own particular use-case where it does fit in, you can add the method as an extension method. I wouldn't recommend it in general, so I don't expect to add it here.