Issue
Can dynamic type in Dart 2 assign to value of difference type and how compile infer them?
For example what is x type in dart 2 and does this compile?
dynamic x = 1;
x = x + "Hello";
Solution
The dynamic
type is special. It really means “trust me, I know what I’m doing” and it turns off some static type checking.
As a type constraint, dynamic
is really equivalent to Object
(you can assign any value to a variable with type dynamic
), but when you try to call methods on the object, you are allowed to try, even if the method doesn’t exist on Object
.
In this case, dynamic x = 1;
works because 1
is assignable to Object
.
Line 2 fails. x = x + "Hello";
tries to call the +
method on 1
with "Hello"
as argument, and even though the +
operator exists, the argument has the wrong type.
You said “trust me, I know what I’m doing”, so the compiler let you do try – there are no static warnings or errors. You got they type wrong, so the runtime stops you before things become unsound.
You could also have written x.argleBargleGlopGlyf(42)
, and the compiler still wouldn’t have stopped you, even if there is no argleBargleGlopGlyf
method anywhere in your program. With great static power comes great dynamic responsibility.
Answered By – lrn
Answer Checked By – Mildred Charles (FlutterFixes Admin)