Switch statement and `runtimeType`

I was looking at dart-lang/language#83 and dart-lang/language#79 to see if type promotion would be useful inside switch statements when I stumbled upon this bug:

class Cat {
  String meow() => 'meow';
}

String foo(dynamic a) {
  switch(a.runtimeType) {
    case String: return 'str';
    case int: return 'int';
    case Cat: return a.meow();
    default: return 'unknown';
  }
}

void main() {
  print(Cat().runtimeType == Cat); // true ✅
  print(foo('abc')); // 'str' ✅
  print(foo(Cat())); // 'unknown' (why not 'meow' ??)
}

I only tested this on DartPad.

Author: Fantashit

1 thought on “Switch statement and `runtimeType`

  1. Now that the new RTI is out we believe the Cat case in the original post will start working. I don’t believe there are any additional action items on our end, so I’ll close this issue.

    I want to emphasize @lrhn‘s advice. It’s best to not rely on runtimeType for almost anything. In addition, its important to be cautious about .runtimeType.toString() – the resulting String is allowed to change and dart2js will use a different string under minification. (e.g. you may get “minified:xQ” instead of “Cat”).

Comments are closed.