Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dart does not throw compile time error when wrong type is assigned to a variable using the if null operator (??) #36964

gtrochimiuk opened this issue May 14, 2019 · 2 comments


None yet
3 participants
Copy link

commented May 14, 2019

Dart VM version: 2.3.0-dev.0.5.flutter-a1668566e5 (Tue Apr 30 20:35:41 2019 +0200) on "macos_x64"

Dart does not throw compile time error when wrong type is assigned to a variable if you use the "if null" operator. Following example compiles without error and then throws a runtime error:

class ExampleClass {}

void main() {
  ExampleClass example = 'string' ?? ExampleClass();

This comment has been minimized.

Copy link

commented May 14, 2019

I believe this is a classical example of the way our unification interacts with implicit downcasts.

The static type of 'string' ?? ExampleClass() is the least supertype of String and ExampleType, which is Object. Since Object is a supertype of ExampleClass, the assignment is allowed statically as an implicit downcast, and it fails at run-time.

With non-nullable types, the 'string' ?? ... will likely become either a warning or an error (the expression cannot be null, so the ?? is irrelevant), and when implicit downcasts are disallowed, that particular error will be caught as well.

Until then, the analyzer option implicit-casts can warn you about all downcasts, which will catch cases like this ... and a lot of other downcasts which are probably perfectly fine.


This comment has been minimized.

Copy link

commented May 14, 2019

I see, thank you for the explanation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.