Dartの定数
Flutterで何かやってみたいと思って始めたけど、Dartに触れるのも初めてなので基本的なところから勉強開始。今回は定数定義(static, final, const)について。
staticについて
staticはクラスのフィールド変数にのみ使用することができ、同一クラスのインスタンスで1つの実体として参照できる。Dart言語ではC++なでのstatic修飾子を付与することでスコープをグローバルにすることはできない。
class Test{
static int _left, _right;
get right => _right;
get left => _left;
set right(int value) => _right = value;
set left(int value) => _left = value;
}
main(){
Test test1 = new Test();
Test test2 = new Test();
test1.right = 5;
print('test1.right = ${test1.right}');
test2.right = 10;
print('test1.right = ${test1.right}');
print('test2.right = ${test2.right}');
}
// 実行結果
test1.right = 5
test1.right = 10
test2.right = 10
finalについて
final修飾子が指定された変数は一度だけ初期化が可能な変数となり、初期化後の変更は不可。
但し、final修飾子が指定された変数のメモリ領域の内容は変更できるらしい。(これはOKなの?)
final int height = 5;
//height = 10; // Error
print('height = $height');
final List<int> width = [ 10, 20, 30 ];
print('width = $width');
width.add(40); // 追加できてしまう
print('width = $width');
// 実行結果
height = 5
width = [10, 20, 30]
width = [10, 20, 30, 40]
constについて
const修飾子が指定された変数はコンパイル時に値が確定されており、finalと同様に値の変更は不可能。
一方、finalでは変更できていたが、constの場合は変数のメモリ領域の値も変更できない。
const int top = 5;
//top = 5; // Error
print('top = $top');
const List<int> bottom = [ 5, 15, 25 ];
print('bottom = $bottom');
//bottom.add(25); // Error
// 実行結果
top = 5
bottom = [5, 15, 25]
普段、C++を使用する機会が多いのでstatic修飾子の違いが一番印象強い。
記法は違うけれどそれほど違和感を感じる内容はなかった。引き続き時間を見つけてDartに取り組みたい。
[参考サイト]