0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

変数宣言(Dart)

Posted at

Dartでは基本的に変数は型推論が効く。
型推論を使う場合はvar宣言する

var age = 0;

修飾子としてはconst, final, lateがある

// コンパイル時定数の宣言
const int age = 39;
// 再代入不可の定数の宣言
final int age = 39;
// 実行時初期化変数の宣言
late int age = calcAge();

constはインスタンス変数としての利用は不可(静的クラスであればOK)。

finalで宣言されたインスタンス変数は、変数自体にインスタンスを再代入することは出来ないが、インスタンスの変更は可能

final currentTime = DateTime.now(); // 実行時に決まる
final List<int> numbers = [1, 2, 3];
numbers.add(4); // OK - リストの中身は変更できる

使い分けのポイントとしては、下記のようになる

  • コンパイル時に値が決まる定数 → const
  • 実行時に一度だけ値が決まる変数 → final
  • パフォーマンス重視で完全不変なオブジェクト → const
  • 使うか使わないかがわからないが、値取得にコストのかかる変数 → late
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?