Why can we not change the variable value if initialises at the time of declaration?
Solution 1:
The var
keyword is used to let Dart automatically assign a type for the variable based on the value you are using to initialize the variable.
If you use var
without providing any initial value, the type of your variable are automatically being assign to dynamic
which allows any type of object to be assigned to the variable. But it also means your program are much less type safe since the analyzer can no longer help you with what type the variable are going to return and what types are allowed when setting the variable.
So in your first example, a
is being assigned the type int
since you provide 10
as the initial value. It is therefore a compile error when you are trying to set a String
as the new value of your int
variable.
In your second example, a
is going to be dynamic
since you are not providing any initial value. So it is not a problem to first give it 10
and later 'John'
since dynamic
allow us to use any type. But that also means that when we try to use a
in our program, Dart cannot make any guarantees about what type of object you are going to get so errors will first be identified at runtime.
Solution 2:
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.