Final
class Car {
final String name;
Car(this.name);
}
void main() {
Car c = Car("소나타");
c.name = "다른자동차"; // Error
}
- Final의 특징
- 무조건 초기화해야 합니다.
- 초기화 되면 바꿀 수 없습니다.
- 런타임에 값이 설정됩니다.
Const
// String 생략시 var로 간주
const primaryColor = "green"; // 컴파일시 초기화 (main 실행 전에 초기화)
final secondaryColor = "red"; // 런타임시 초기화
class Button {
String text;
Button(this.text);
}
void main() {
primaryColor = "blue"; // Error
}
- Const의 특징
- 컴파일 타임에 값이 설정됩니다.
- 변수가 불변임을 보장합니다.
Final과 Const를 활용, 객체를 싱글톤으로 관리
const primaryColor = "green";
const secondaryColor = "red";
class Button {
final String text; // text 필드는 한 번 설정되면 변경할 수 없습니다.
const Button(this.text); // const 추가 1
}
void main() {
// const가 붙으면 똑같은 객체가 있는지 메모리에서 검색
Button b1 = const Button("로그인"); // const 추가 2
Button b2 = const Button("로그인");
Button b3 = const Button("로그아웃");
print(b1.hashCode);
print(b2.hashCode); // b1과 주소 동일
print(b3.hashCode); // b1과 주소 다름
}
- const 생성자는 객체를 상수로 만듭니다.
- const 키워드로 Button을 생성할 경우 메모리에서 같은 객체를 재사용합니다.
Share article