Dart言語 コンストラクタ

クラスと同じ名前の関数がコンストラクタ

生成的コンストラクタ(一般的なコンストラクタ)

1
2
3
4
5
6
7
8
9
class Color {
int red;
int green;
int blue;
Color({int red, int green, int blue}) {
this.red = red;
this.green = green;
this.blue = blue;
}

自動フィールド初期化

  • Dartで使われる一般的な書き方
  • 上のコードと同じ意味
1
2
3
4
5
6
7
class Color {
int red;
int green;
int blue;
// 同名のフィールドに自動代入する
Color(this.red, this.green, this.blue);
}

名前付きコンストラクタ

  • クラスに複数のコンストラクタを実装できる
  • それぞれのコンストラクタの意味を明確に出来る
1
2
3
4
5
6
7
8
9
10
11
12
class Color {
int red;
int blue;
int green;

// 別の引数を受け取るコンストラクタを作成
Color.fromString(String colorText) {
this.red = int.parse(colorText.substring(0, 2), radix: 16);
this.blue = int.parse(colorText.substring(2, 4), radix: 16);
this.green = int.parse(colorText.substring(4, 6), radix: 16);
}
}

コンストラクタのリダイレクト

1
2
3
4
5
6
7
8
9
10
11
12
class Child extends Base {
// 親クラスの「名前付きコンストラクタ」を呼び出す
Child(String value): super.fromString(value);

// 親クラスの「通常のコンストラクタ」を呼び出す
Child.ex(): super('test') {
//...
};

// 自クラスの別の「名前付きコンストラクタ」を呼び出す
Child.delegate(): this.fromString('');
}

初期化リスト

  • コンストラクタ本体を実行する前に、インスタンス変数を初期化できる
1
2
3
4
5
6
7
8
class Line {
final int length;
final Color color;

// 何か処理を実行してからフィールドに代入する
Line({@required this.length, @required String colorText}):
this.color = Color.fromString(colorText);
}

初期化される処理の順序

  1. 初期化リスト (initializer list)
  2. スーパークラスのコンストラクタ
  3. 子クラスのコンストラクタ

初期化リスト + assert機能

1
2
3
4
5
6
7
8
9
class Article {
final String title;
final String body;

// 引数の条件確認を行う
Article({@required this.title, @required this.body}):
assert(title != null),
assert(body != null);
}
1
2
3
4
5
6
7
class Item extends Base {
final String name;

Item({@required this.name}):
asesrt(name != null),
supser(); // 親クラスのコンストラクタを呼び出す場合は最後に書く
}

ファクトリコンストラクタ

  • ファクトリコンストラクタはインスタンスが作成されない
  • シングルトンのデザインパターンで利用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
clas GlobalContext() {
static GlobalContext _instance;

// 「_」から始まるのでprivateなコンストラクタ
GlobalContext._() {
//...
}

// ファクトリコンストラクタで「生成的コンストラクタ」を使う
factory GlobalContext() {
if (_instance == null) {
_instance = GlobalContext._();
}
return _instance;
}

// ファクトリコンストラクタで「名前付きコンストラクタ」を使う
factory GlobalContext.getWithRefresh() {
_instance = null;
return GlobalContext();
}
}

定数コンストラクタ

  • コンパイル時に定数オブジェクトをインスタンス化したい場合に利用
  • コンストラクタには「const」キーワードを付け、「const」キーワードでインスタンスを生成
1
2
3
4
5
6
7
8
9
10
11
12
class Pet{
final name;
const Pet(this.name);
}

final dog = const Pet('Pochi');

void main(){
final Pet cat = new Pet('Mike');
print(dog.name); // => Pochi
print(cat.name); // => Mike
}

コメント

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×