Search code examples
dartdart3dart-pattern-matching

What's the recommended syntax for matching types in Dart 3?


Dart 3 has two syntaxes for matching types:

switch(myObject) {
  case TypeA(): // With parameter destructuring
  case TypeB _: // Without parameter destructuring
}

If no further destructuring is needed, which should be used? Is one more performant than the other?


Solution

  • I'll recommend case TypeB _: as the general way to write type tests that do nothing else.

    The reason is that it allows any type syntax, where TypeA() only allow type names, so if you ever need to match a function, you can write it directly as:

      case void Function() _: .... // Works
    

    You can use () for any type as well, you just need a helper type alias, so the type has the correct format:

    typedef typeof<T> = T;
    // ...
      case typeof<void Function()>(): ... // Works too.