Based on that simple class:
class User { String? name; int? id; }
I'm not sure what is the difference between:
var user = User();
or:
User user = User();
If someone can shed some light on this I'll be more than happy.
CodePudding user response:
There's no practical difference in this case. When you use the var
keyword, the type will be inferred by the compiler, whereas declaring it as User
is simply a way to explicitly define the type.
There are some cases where it would make some difference though, such as when instantiating a generic type, like List
.
If you type:
var list = [1, 2, 3];
Then list
will have a type of List<int>
. But you might have wanted a list of double
s. In that case, you could write:
List<double> list = [1, 2, 3];
And you would be assured that list
would have the type you want (though of course in this case you could also simply write var list = [1.0, 2.0, 3.0]
).
It's also helpful when instantiating an empty list, since in that case there are no values in the list from which the compiler can infer the type.