Dart语言入门——const修饰符
const修饰的对象是在编译时创建的,所以其值必须是在编译时就就可以确定的,且创建后其值就不可再变
const修饰符的相关知识点比较多,这里结合实例一个个说明
const声明的变量必须马上初始化
void main() {
const String s; // The const variable 's' must be initialized.错误
s = ''; // Constant variables can't be assigned a value.
}
报如下错误
Error compiling to JavaScript:
main.dart:2:17:
Error: The const variable ';' must be initialized.
const String s; // The const variable 's' must be initialized.错误
^
main.dart:3:3:
Error: Setter not found: 's'.
s = '';
^
Error: Compilation failed.
const变量创建后,值不可再改变
void main() {
const s = '野猿新一';
s = '野猿新二'; // 报Constant variables can't be assigned a value.错误
}
变量不可以同时声明'var' 和 'const'
void main() {
const var s = 's'; // 报Members can't be declared to be both 'var' and 'const'.错误
}
const声明变量,类型可以省略
void main() {
const String s1 = 'Hello';
const s2 = 'World'; // 类型可以省略
print(s1);
print(s2);
}
const关键字也可以放在创建对象的时候
void main() {
const list1 = {1, 2, 3}; // const关键字用在声明的地方
var list2 = const {1, 2, 3}; // const关键字也可以用在创建对象的地方
print(identical(list1, list2)); // 结果为true
}
const对象的值必须在编译时就可确定
如果是一个表达式,其结果值也必须在编译时可马上确定的,比如1+1
void main() {
const i = 1 + 1;
print(i); // 结果输出2
}
或者通过常量构造函数来创建对象
void main() {
var point = const Point(1, 2);
}
class Point {
int x;
int y;
const Point(this.x, this.y);
}
若表达式的结果值是运行时的,则会报错
void main() {
const time = DateTime.now();
print(time);
}
Error compiling to JavaScript:
main.dart:2:25:
Error: Cannot invoke a non-'const' constructor where a const expression is expected.
const time = DateTime.now();
^^^
Error: Compilation failed.
这是const和final的区别之一, final变量的值是可以在运行时才确定的
void main() {
final time = DateTime.now();
print(time); // 输出运行时的当前时间,如2019-10-17 14:17:55.388
}
const对象的值不可变是深度递归的,其内部成员的值也都是不可变的
例如创建一个const list,一旦创建,其成员的值也都不可变
void main() {
const list = [1, 2, 3];
list[0] = 10;
print(list);
}
报如下错误
Uncaught exception:
Unsupported operation: indexed set
而这也是const和final的区别之一,final定义的list,其内部的成员是可变的,如下代码是可以正常运行
void main() {
final list = [1, 2, 3];
print(list);
list[0] = 10;
print(list);
}
运行结果如下
[1, 2, 3]
[10, 2, 3]
相同的const对象只会被创建一次
如下代码虽然创建了两个对象list1和list2,以为其内容一致且都是const对象,所以其指向的是同一对象
void main() {
const list1 = [1, 2, 3];
const list2 = [1, 2, 3];
print(list1 == list2); // 输出结果为true
print(identical(list1, list2)); // 输出结果为true
}
这是const和final的又一个区别之一,final声明的变脸,即使内容相同,也是重新创建新的对象,而不是共用
void main() {
final list1 = [1, 2, 3];
final list2 = [1, 2, 3];
print(list1 == list2); // 输出结果为false
print(identical(list1, list2)); // 输出结果为false
}
const也可以用来创建常量构造函数
常量构造函数可以用来创建const对象,关于常量构造函数的详细说明及注意点,可以参考Dart const常量构造函数详解
void main() {
var point = const Point(1, 2);
}
class Point {
int x;
int y;
const Point(this.x, this.y);
}