在 dart 中,有一个varwhich 的意思dynamic type。
当声明一个局部变量时,我可以写:
String name = "Freewind";
或者
var name = "Freewind";
一开始我以为它们是一样的,因为编辑器应该可以推断出nameis的类型String,但我很快发现:
void hello(String name) { print("hello, $name"); }
int n = 123;
hello(n); // editor will give an warning here
var m = 456;
hello(m); // but will not here
我尝试使用 DartEditor(基于 Eclipse)和 IDEA,发现在hello(m). 似乎他们将mas 视为dynamic, not int,因此他们不发出警告。
如果我理解正确,我们应该尽可能多地声明类型以获得类型安全检查,对吗?但我喜欢var它,因为它更短,不需要复制类型信息。
还是因为 Dart 的编辑不够强大而没有警告,我们以后会收到警告?