Skip to content

No type inference from is! #35019

Closed
Closed
@jamesderlin

Description

@jamesderlin
  • 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.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).closed-duplicateClosed in favor of an existing report

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions