1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Dart] const vs final

Posted at

導入

const final どちらも変数を値を書き換えられないものということは理解できる。

void main() {
  
  const int myConst = 1;
  final int myFinal = 2;
  
  myConst = 3; // error
  myFinal = 4; // error
}

どのような違いがあるか。

const

定義時のみ定数を代入できる。

NG
void main() {
  
   const int myConst; //定義 //error
  
   myConst = 1; //代入
}

NG
void main() { 
  
  const DateTime myConst = DateTime.now(); // error
}
OK
void main() {
  
  final int myFinal = 2; //OK
}

final

定義した後でも代入可能。
定数以外のインスタンス等も確保可能。

void main() {
  
  final DateTime myFinal;  //定義
  myFinal = DateTime.now();  //代入
  
  print('myFinal: $myFinal'); //2022-02-26 16:23:54.138
}

まとめ

const final
定数のみ定義可能 定数に限らず定義可能
定義時のみ代入可能 定義後も代入可能
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?