Where does ‘var’ and ‘dynamic’ fit into the object tree?
dynamic are not objects (or types) themselves so they don’t fit into the object tree.
var is a keyword and is short for “variable”. When you use it you are letting Dart infer the type from whatever the value of the variable is. For example:
var x = 1;
1 is an integer, Dart infers the type to be
int. You use
var to tell Dart that you want to change the value later. Like this:
var x = 1; x = 2;
const all are related keywords because they all let Dart infer the type.
dynamic is also not really a type by itself. Rather, you use this keyword to tell Dart that you don’t want to use any type checking. This is fine:
dynamic x = 1; x = 'hello'; x = true; x = null;
If you want to compare
dynamic to a type, it is most similar to
Object? since everything is a subtype of
Object?, even nullable values. This is fine:
Object? x = 1; x = 'hello'; x = true; x = null;
However, saying that you can use any object type (
Object?) is not quite the same as saying that you don’t care about the type (
@suragch makes sense. Thank you for your reply.
Just to clarify — I can’t see anything about
dynamic or object tree at the page 62 of PDF version of Dart Apprentice: Fundamentals book. Looks like you are talking about another book, aren’t you?
dynamic are discussed elsewhere in Dart Apprentice: Fundamentals, just not on that particular page. These keywords occur in the same location when declaring a variable as type names like
String do, so it’s easy to assume that
dynamic should also fit somewhere into the hierarchy of Dart types represented by the Object Tree diagram. I believe that’s what led to the original question from the reader above.