dart-lang / core

This repository is home to core Dart packages.
https://pub.dev/publishers/dart.dev
BSD 3-Clause "New" or "Revised" License
19 stars 7 forks source link

[Proposal] Add `firstWhereType` #677

Closed SamuelGadiel closed 1 month ago

SamuelGadiel commented 5 months ago

We already have whereType, but it would be great to get the first occurrence of the given type.

Here's a use case where this could come in hand.

final results = await Future.wait(
  [
    _metadataService.getTableMetadata(tableId),
    _dataService.getTableData(tableId),
  ],
  eagerError: true,
);

final metadata = results.whereType<TableMetadata>().first;
final data = results.whereType<TableRawData>().first;

It could be replaced with

final metadata = results.firstWhereType<TableMetadata>();
final data = results.firstWhereType<TableRawData>();
mateusfccp commented 2 months ago

This is potentially more efficient than .whereType().first, as we can stop in the first element with the given type.

lrhn commented 1 month ago

Using .whereType().first will also stop at the first element that has the type.

I'm not completely against this, but also not convinced that .whereType<T>.first isn't good enough. We can add specialized functions for every combination of two or more basic operations, but that gets unwieldy and not necessarily more readable. Doing .mapWhereMap(convert1, test, convert2) isn't more readable than .map(convert1).where(test).map(convert2), I can understand the latter compositionally, I need to learn what the former means, along with every other combination we choose to add.

natebosch commented 1 month ago

Yeah I think these are too specialized for this package. I'll close this issue as not planned since I don't anticipate expanding the surface area we support to include these APIs.