Difference between “var” and “dynamic” type in Dart?

前端 未结 11 2279
攒了一身酷
攒了一身酷 2021-01-30 10:25

According to this article:

As you might know, dynamic (as it is now called) is the stand-in type when a static type annotation is not provide

11条回答
  •  天命终不由人
    2021-01-30 10:44

    var, like final, is used to declare a variable. It is not a type at all.

    Dart is smart enough to know the exact type in most situations. For example, the following two statements are equivalent:

    String a = "abc"; // type of variable is String
    var a = "abc";    // a simple and equivalent (and also recommended) way
                      // to declare a variable for string types
    

    On the other hand, dynamic is a special type indicating it can be any type (aka class). For example, by casting an object to dynamic, you can invoke any method (assuming there is one).

    (foo as dynamic).whatever(); //valid. compiler won't check if whatever() exists
    (foo as var).whatever(); //illegal. var is not a type
    

提交回复
热议问题