Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `if (var = null)` compile in dart?

Tags:

dart

I've recently came across this question How do I solve the 'Failed assertion: boolean expression must not be null' exception in Flutter

where the problem comes from a should be invalid code that gets treated as valid.

This code can be summarized as :

int stuff;
if (stuff = null) { // = instead of ==
}

But why does this code compiles ? As the following will not.

int stuff;
if (stuff = 42) {
}

With the following compile error :

Conditions must have a static type of 'bool'.

So I'd expect out of consistency that if (stuff = null) to gives the same error.

like image 503
Rémi Rousselet Avatar asked Jan 28 '23 20:01

Rémi Rousselet


2 Answers

null is a valid value for a bool variable in Dart, at least until Dart supports non-nullable types.

bool foo = null;

or just

bool foo;

is valid.

Therefore in the first case there is nothing wrong from a statical analysis point of view.

In the 2nd case the type int is inferred because of the assignment, which is known to not be a valid boolean value.

bool foo = 42; 

is invalid.

like image 159
Günter Zöchbauer Avatar answered Feb 01 '23 19:02

Günter Zöchbauer


When you say var stuff; with no initial value it is giving stuff a static type of dynamic. Since dyamic might be a bool, it's legal to assign null to a variable of type dynamic, and it's legal to use a possibly null bool in a conditional, the compiler doesn't flag this. When you say int stuff; the compiler knows that stuff could not be a bool. The reported error in that case is cause by the static type of stuff, not the assignment to null.

Edit: Got the real answer from someone who knows how to read the spec.

The static type of an assignment expression is the right hand side of the assignment. So the expression stuff = null has the static type of Null which is assignable to bool.

The reasoning is that the value of an assignment is the right hand side, so it makes sense to also use it's type. This allows expressions like:

int foo;
num bar;
foo = bar = 1;
like image 36
Nate Bosch Avatar answered Feb 01 '23 19:02

Nate Bosch