Skip to content

Support switch in Collection Literals #4354

Closed as duplicate of#2124
Closed as duplicate of#2124
@rubenferreira97

Description

@rubenferreira97

Dart supports if and for in collection literals, and even if-case. However, there's currently no support for switch inside collection literals, which limits expressiveness and leads to repeated expressions.

Example (today, using if-case):

final map = {
  for (final pair in pairs.split(';'))
    if (pair.split('=') case [final key]) key: '',
    else if (pair.split('=') case [final key, final value]) key: value,
};

This repeats split('=') and is harder to maintain (e.g. add cases).

Proposed (with switch support and implicit variables):

final map = {
  for (final pair in pairs.split(';'))
    switch (pair.split('=')) {
      case [final key]: key: '',
      case [final key, final value]: key: value,
    }
};

I believe switch in this context shouldn't require exhaustiveness—unmatched cases could simply be skipped, just like with if. If exhaustiveness is needed, a switch expression could be used instead.

I also understand that this level of logic might be considered too much for collection literals, but personally I've encountered cases where it would be useful. I'm filing this issue to open up discussion and gather feedback.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions