Skip to content

Support exhaustive pattern match on a generic type argument #4464

@Zekfad

Description

@Zekfad

Currently there are no good way to perform an exhaustive check for a type arguments of a generic function.
There are two methods with drawbacks:

  • ex. f1: Perform direct Type comparison - not exhaustive and error prove if hierarchy changes, no hints if type is unrelated:
  • ex. f2: Perform exhaustive check on some generic object - requires allocation of new runtime object (likely bad for performance).

I believe there should be a better mechanism for this, such as special syntax which will perform match without allocating generic container or some internal symbol which will serve as synthetic container instead of List in example.

I think this will help with performance, dead code elimination and reduce developer induced errors.

sealed class A {}
final class B extends A {}
final class C implements A {}

String f1<T extends A>() => switch(T) {
    const (B) => 'B',
    const (C) => 'C',
    const (A) => throw StateError('Unbound type T of A.'),
    // no hint for unrelated type
    const (int) => throw StateError('Impossible state.'),
    // not exhaustive
    _ => throw StateError('Impossible state.'),
};

// Requires dynamic object allocation and check for unrelated "List"
String f2<T extends A>() => switch(<T>[]) {
    List<B>() => 'B',
    List<C>() => 'C',
    List<A>() => throw StateError('Unbound type T of A.'),
};

void main() {
  print(f1<C>());
  print(f2<C>());
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions