dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.23k stars 1.57k forks source link

Different error message between compiler and analyzer when using bool? in if-statement #56697

Open julemand101 opened 1 month ago

julemand101 commented 1 month ago

Reproduced with the following:

Dart SDK version: 3.5.2 (stable) (Wed Aug 28 10:01:20 2024 +0000) on "windows_x64"
Dart SDK version: 3.6.0-228.0.dev (dev) (Sat Sep 7 17:07:10 2024 -0700) on "windows_x64"

Code:

void main() {
  bool? b = getBool();

  if (b) {}
}

bool? getBool() {
  return null;
}

Output from dart analyze:

> dart analyze
Analyzing AdventOfCode2022...

  error • bin\advent_of_code_2022.dart:4:7 • A nullable expression can't be used as a condition. Try checking that the value isn't 'null' before using it as a condition. •
          unchecked_use_of_nullable_value

1 issue found.

Output from dart .\bin\advent_of_code_2022.dart:

> dart .\bin\advent_of_code_2022.dart
bin/advent_of_code_2022.dart:4:7: Error: A value of type 'bool?' can't be assigned to a variable of type 'bool' because 'bool?' is nullable and 'bool' isn't.
  if (b) {}
      ^

I feel the error message from the compiler are kinda misleading since it tells about some variable assignment which are confusing since there are no variable being assigned in if (b) {}. The analyzer are more clear about what is going on.

dart-github-bot commented 1 month ago

Summary: The analyzer and compiler produce different error messages when a nullable boolean (bool?) is used in an if statement. The analyzer correctly identifies the issue as an unchecked use of a nullable value, while the compiler incorrectly suggests a type assignment error.

pq commented 1 month ago

@bwilkerson: not sure about triaging this one; could you take a look?