Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "var" and "dynamic" type in Dart?

Tags:

dart

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 provided.

So, what is the difference between dynamic and var? When to use?

like image 644
Gero Avatar asked Sep 14 '12 00:09

Gero


1 Answers

dynamic is a type underlying all Dart objects. You shouldn't need to explicitly use it in most cases.

var is a keyword, meaning "I don't care to notate what the type is here." Dart will replace the var keyword with the initializer type, or leave it dynamic by default if there is no initializer.

Use var if you expect a variable assignment to change during its lifetime:

var msg = "Hello world."; msg = "Hello world again."; 

Use final if you expect a variable assignment to remain the same during its lifetime:

final msg = "Hello world."; 

Using final (liberally) will help you catch situations where you accidentally change the assignment of a variable when you didn't mean to.

Note that there is a fine distinction between final and const when it comes to objects. final does not necessarily make the object itself immutable, whereas const does:

// can add/remove from this list, but cannot assign a new list to fruit. final fruit = ["apple", "pear", "orange"]; fruit.add("grape");  // cannot mutate the list or assign a new list to cars. final cars = const ["Honda", "Toyota", "Ford"];  // const requires a constant assignment, whereas final will accept both: const names = const ["John", "Jane", "Jack"]; 
like image 197
John Evans Avatar answered Sep 28 '22 03:09

John Evans