-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Switch statement and runtimeType
#35052
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
It's a bug in dart2js. Or two bugs, actually. First if all, you should not be allowed to use Second, the dart2js implementation of switch assumes that you can use identity for checking (since the values should not override (I'm filing this as a dart2js error for the switch case using identity since allowing So, example: main() {
switch(Symbol("foo")) {
case #foo: print("yes"); break;
default: print("no");
}
} This prints "no" in dart2js. It must print "yes". If we ever allow |
Since all implementations allow it anyway, we now intend to formally allow |
Hello from 2020 👍 class Cat {
String meow() => 'meow';
}
String foo(dynamic a) {
switch (a.runtimeType.toString()) {
case 'String':
return 'str';
case 'int':
return 'int';
case 'Cat':
return a.meow();
default:
return 'unknown';
}
}
void main() {
print(foo('abc')); // 'str' ✅
print(foo(42)); // 'int' ✅
print(foo(Cat())); // 'meow' ✅
// prints 'yes' ✅
switch (Symbol("foo").toString()) {
case 'Symbol("foo")':
print("yes");
break;
default:
print("no");
}
} |
dart2js has a new implementation of runtime Type objects that are canonicalized. However, this does not mean that the original program will behave as expected. The types |
With ahead-of-time compilation, we cannot really assume anything about compiler-provided implementation types. Even if dart2js canonicalizes types, the compiler front-end won't know that, and the same code might fail when compiled for a different back-end. That's why we special-cased constant (That is really a hole in the specification - it talks about creating objects at compile-time, but that only makes sense for classes which are available at compile-time, not those which are provided by the run-time system. In fact, the specification kind-of assumes that it does know the whole program, which just isn't true). We make no promises that integer values return I recommend never using |
Now that the new RTI is out we believe the 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 |
Use it, its work fine.
|
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:
I only tested this on DartPad.
The text was updated successfully, but these errors were encountered: