Skip to content

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

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

Closed
gtrochimiuk opened this issue May 14, 2019 · 3 comments
Labels
area-language Dart language related items (some items might be better tracked at github.com/dart-lang/language).

Comments

@gtrochimiuk
Copy link

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();
}
@lrhn
Copy link
Member

lrhn 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.

@gtrochimiuk
Copy link
Author

I see, thank you for the explanation.

@mit-mit mit-mit added the area-language Dart language related items (some items might be better tracked at github.com/dart-lang/language). label May 14, 2019
@natebosch
Copy link
Member

Closing since NNBD will also disable implicit casts and there are no specific actions to take on this issue.

dart-lang/language#192

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-language Dart language related items (some items might be better tracked at github.com/dart-lang/language).
Projects
None yet
Development

No branches or pull requests

4 participants