3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RecordのIterableをいい感じにmapしたい

Last updated at Posted at 2024-05-07

RecordのListをmapしたい

mapの引数はT toElement(E e)なので
final (id, name) = e;
などとするか
$1などのわかりづらいgetterを使わないといけない。

void main() {
  List<(int, String)> recordList = [
    (1, '山田'),
    (2, '佐藤'),
    (3, '鈴木'),
  ];

  recordList.map((e) {
    final (id, name) = e;
    return id.toString() + name;
  });

  recordList.map((e) => e.$1.toString() + e.$2);
}

以下のような拡張を用意する

extension IterableRecord2<T1, T2> on Iterable<(T1, T2)> {
  Iterable<T> mapRecord<T>(T toElement(T1 t1, T2 t2)) =>
      map((e) => toElement(e.$1, e.$2));
}

そうするとこう書ける、いい感じ

void main() {
  List<(int, String)> recordList = [
    (1, '山田'),
    (2, '佐藤'),
    (3, '鈴木'),
  ];

  recordList.mapRecord((id, name) => id.toString() + name);
}

量産する

extension IterableRecord3<T1, T2, T3> on Iterable<(T1, T2, T3)> {
  Iterable<T> mapRecord<T>(T toElement(T1 t1, T2 t2, T3 t3)) =>
      map((e) => toElement(e.$1, e.$2, e.$3));
}

extension IterableRecord4<T1, T2, T3, T4> on Iterable<(T1, T2, T3, T4)> {
  Iterable<T> mapRecord<T>(T toElement(T1 t1, T2 t2, T3 t3, T4 t4)) =>
      map((e) => toElement(e.$1, e.$2, e.$3, e.$4));
}

パッケージ!使ってみてね😁

3
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?