Closed
Description
- Dart SDK 2.0.0
- Linux, also tested with dartpad
The following code is accepted without error:
class Base {
}
class Derived extends Base {
void foo() {
}
}
void main() {
Base d = Derived();
if (d is Derived) {
d.foo();
}
}
However, if I invert the d is Derived
check:
if (d is! Derived) {
} else {
d.foo();
}
then I get an error:
Error: The method 'foo' isn't defined for the class '#lib1::Base'.
(The same thing happens if I try !(d is Derived)
.)
This seems inconsistent. Couldn't we internally invert is!
and the if
-else
clauses to achieve the same behavior as the first version?
(And if anyone is wondering why I don't just always use the first version, there are cases where one path has much more code than the other, and for readability I prefer to have the simpler block first, e.g.:
if (d is! Derived) {
// assert(false); // Or run some other failure handler
} else {
d.foo();
// Followed by a lot more code.
}
Of course, in that particular case, it be even nicer if:
assert(d is Derived);
d.foo();
worked.)