I am learning dart and this behavior of dart is annoying me
var a=10;
a="John"; //it generates an error, because a has integer data-type and we can't assign
//string or the value of any other data type because we have assigned an
//integer value
but at the same time, dart allows us to write
var a;
a=10;
a="John";
print (a) //it displays John
it means that we can't assign the value of any other data type when a variable initializes at the time of declaration but we can assign the value of any other data type if the variable declares in one line and initializes at the second line. Why does dart work in this way?
That's because var
means dart will assign the type of variable itself.
In first case, the dart assigned variable a
as int
type because it was given a value during initialisation.
But in second case, the dart assigned variable a
as dynamic
and that's why you can assign it either a string or int later on.