dartswitch-statement

Explanation of type comparison using switch-case in Dart


Why doesn't this work

Type type = double;

switch (type) {
  case int:
    print('int');
  case double:
    print('double');
}

But this does

switch (type) {
  case const (int):
    print('int');
  case const (double):
    print('double');
}

What is const (Type) for? It looks like turning a class or type (hereinafter simply class) into its constant form. Well, firstly, turning something into a constant seems wrong to me, like, we just define them and forbid redefining them. What's the point of making something immutable only for a certain period, instead of just not changing it? Secondly, isn't the class itself immutable during runtime, which in essence can be perceived as a constant?

Why not just use the first form to write switch-case for comparing types? Either I don't understand what const (Type) does, or I don't understand what a class is (if so, then I hope only in Dart).


Solution

  • The code works.

    The question might be promted by lint warning about not using case int:.

    It's discouraged because people have mistakenly written switch (someValue) { case int: ...} and expected it to check whether the value is an integer. Instead it checks if the value is a Type object equal to int, with no warning about it not being able to match (because it could hypothetically be an instance of a sub class of the switched-on type that implements Type).

    You should use int _ or int() to check whether the value is an integer, and to avoid the lint warning, you can use == int or const (int) to emphasize that you really do want to compare to a Type object. The const (expression) is a way to put any constant expression into a pattern. Writing const (int) doesn't mean anything other than int, it's only there to silence the lint by telling it that you know you're comparing to a constant Type object.

    Generally, comparing Type objects is usually a sign of a class design that doesn't match the problem. It's also usually fragile and error prone code.