728x90

둘 다 불변의 상수를 의미하는 keyword 이지만 const 가 더욱 불변의 강도가 강하다.

final : final 지시어는 어떤 변수를 참조하는 값이 한번 설정되면 다른 값으로 변경될 수 없다는 것을 의미한다.

          run-time constant 이며, APP 실행과정에서 값이 정해진다.

const : 한번만 설정할 수 있지만 compile-time constant로 컴파일 타임에 그 값을 알 수 있어야 한다.

            Java 언어에서는 public static final 이라는 복잡한 키워드를 사용하지만,

            다트 언어에서는 const 로 단순화할 수 있다.

 

void main() {
 String name1 = '홍길동';
 print(name1);
  
 const String name2 = '홍길동'
 print(name2);
  
 final String name3 = '홍길동'
 print(name3);
  
}

 

 

void main() {
  final name = '홍길동'// 타입 생략 가능
  print(name);
}
 

 

 

void main() {
 String name1 = '홍길동';
 name1 = '이순신';
 print(name1);
  
 const String name2 = '홍길동'
 name2 = '이순신'// 에러
 print(name2);
  
 final String name3 = '홍길동'
 name3 = '이순신'// 에러
 print(name3);
  
}

 

The Const keyword in Dart behaves exactly like the final keyword. 

The only difference between final and const is that the const makes the variable constant from compile-time only. Using const on an object, makes the object’s entire deep state strictly fixed at compile-time and that the object with this state will be considered frozen and completely immutable.

void main() {
  final x1 = DateTime.now();
  print(x1);
  
  // Error: Cannot invoke a non-'const' constructor where a const expression is expected.
  const x2 = DateTime.now(); // 컴파일 타임에 값을 알 수 없어 에러 발생
}

DateTiem.now()는 APP 실행시 정해지는 값이다.

 

'Flutter 앱 > Dart 언어' 카테고리의 다른 글

Dart Class(클래스)  (0) 2022.06.27
Dart Asynchronous programming(비동기 프로그래밍)  (0) 2022.06.23
Dart function(함수)  (0) 2022.06.22
Dart Type 검사(is, is!)  (0) 2022.06.22
Dart 변수 var, dynamic, num, int, double  (0) 2022.06.22
블로그 이미지

Link2Me

,