Reputation: 6921
In the following code:
main() {
print('Starting....');
int x = 10;
int y = x > 3 ? 'aaa' : 7;
print(y);
}
This is the output:
Starting....
Unhandled exception:
type 'String' is not a subtype of type 'int'
#0 main (file:///tmp/main.dart:4:12)
#1 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
#2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
why isn't there a compile time error on the assignment to y? Why only runtime error?
version: Dart VM version: 2.8.4 (stable) (Unknown timestamp) on "linux_x64"
Thanks!
Upvotes: 2
Views: 59
Reputation: 31269
The reason is that Dart does still try to make implicit type casts as default behavior. So in this case, Dart will automatically assume you can cast the String
into a int
. This behavior can be disabled and will also be disabled by default when non-nullable types are supported:
https://dart.dev/guides/language/analysis-options#enabling-additional-type-checks
You can add the following to analysis_options.yaml
(I do also recommend to add implicit-dynamic: false
but this is not necessary for this specific issue):
analyzer:
strong-mode:
implicit-casts: false
And you will then get an error from the analyzer:
Analyzing bin/stackoverflow.dart...
error • A value of type 'Object' can't be assigned to a variable of type 'int'. • bin/stackoverflow.dart:4:11 • invalid_assignment
1 error found.
The reason why the error are saying Object
is because Dart has analyzed x > 3 ? 'aaa' : 7
into the return type of Object
since that is the only thing in common for int
and String
.
Upvotes: 3
Reputation: 106
You are trying to parse the string 'aaa' in a type called int. 'aaa' is not a number so error.
String y = x > 3 ? 'aaa' : '7';
or do:
int y = x > 3 ? 2 : 7;
Upvotes: -2