Non-null inference after null check with class fields

42 views
Skip to first unread message

Alec Henninger

unread,
Jan 5, 2021, 3:43:16 AM1/5/21
to Dart Misc
Hi dart-misc,

As I'm migrating to NNBD, I'm adding a! lot! of! exclamation! points!. Many (most?) of these should be inferable automatically IMO. Example:

void greet(String who) {
  print("Hello $who");
}

class Test {
  String? who = random.nextBool() ? "Bob" : null;

  void test() {
    if (who != null) {
      // Analyzer complains even though who is not null
      greet(who);
    }
  }
}


The call to greet(who) inside the class method test gives an analyzer error.

You get similar errors trying to assign the nullable type to a non-null variable after the null check.

A similar scenario but with a variable declared inside a method does not give any errors:

void test() {
  String? who = random.nextBool() ? "Bob" : null;
  if (who != null) {
    // Analyzer knows this can't be null
    greet(who);
  }
}

I'm wondering if there is an issue open for this already (hard to find) or if this is intended behavior.

Thanks!

Alec

Jacob Bang

unread,
Jan 5, 2021, 3:59:12 AM1/5/21
to mi...@dartlang.org
Take a look at the answer I gave on stackoverflow to a similar question:
https://stackoverflow.com/a/65457221/1953515
> --
> For more ways to connect visit https://dart.dev/community
> ---
> You received this message because you are subscribed to the Google Groups "Dart Misc" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to misc+uns...@dartlang.org.
> To view this discussion on the web visit https://groups.google.com/a/dartlang.org/d/msgid/misc/86a89af4-943a-4595-8f52-2c88643b23bfn%40dartlang.org.



--
Jacob Bang / julemand101
Message has been deleted

Bob Nystrom

unread,
Jan 7, 2021, 5:20:35 PM1/7/21
to General Dart Discussion


On Tue, Jan 5, 2021 at 7:00 AM Alec Henninger <aleche...@gmail.com> wrote:
Hrm, unfortunate, but makes sense. I missed the "class fields" exception on the https://dart.dev/null-safety page.

I suppose it would be nice if either the analyzer could see that a class or field was not overridden, or there was a way to prevent overrides (which can be nice for other cases of course).

Yeah, this is a known pain point with null safety. It's the biggest issue we've noticed when migrating our own code to null safety, by a pretty big margin. We have some ideas on how to improve it, and some of those like you suggest involve being able to detect cases where a field can soundly be promoted and enable it there. There are a lot of tricky edge cases and subtleties which is one of the reasons we didn't get something like this working with the main null safety release, but I think there's room to improve things in the future.

In practice, I find this issue surprising and annoying, but not particularly difficult to manage once you're aware of and internalize the limitation.

Cheers!

– bob

Reply all
Reply to author
Forward
0 new messages