Skip to content

Type promotion doesn't work on "is!" #80

Closed
@munificent

Description

@munificent

From: @jamesderlin (dart-lang/sdk#35019):

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.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions