dart-lang / language

Design of the Dart language
Other
2.66k stars 205 forks source link

Record pattern matching nullability deduction #3243

Open maprohu opened 1 year ago

maprohu commented 1 year ago

Hi,

I would like to implement a method in Dart, something like the following:

int nullFirstCompare<T extends Comparable<T>>(T? a, T? b) {
  return switch ((a, b)) {
    (null, null) => 0,
    (null, _) => -1,
    (_, null) => 1,
    (final a, final b) => a.compareTo(b), // does not compile
  };
}

So, my hope would be that by the 4th case in the switch the Dart compiler would deduce that none of the record fields can be null. It does not, therefore the 4h case does not compile.

I wonder if this is a limitation or a bug in the compiler. Also if there is some elegant way to rewrite this code to make it work with the current Dart compiler.

% dart --version
Dart SDK version: 3.0.6 (stable) (Tue Jul 11 18:49:07 2023 +0000) on "macos_arm64"

Thanks!

Marton

julemand101 commented 1 year ago

I suggest you edit the issue to have a more fitting title of your problem.

eernstg commented 1 year ago

We have discussed this topic before. In particular, this issue is somewhat similar: https://github.com/dart-lang/language/issues/2503, but also https://github.com/dart-lang/language/issues/2896 and https://github.com/dart-lang/language/issues/2641. In https://github.com/dart-lang/language/issues/2977 the main topic is lists, but it is still somewhat similar.

In short: That would be nice, but the discussions about how to deal with it are ongoing.

I'll transfer this issue to the language repository, it's a better fit there.