Dart言語仕様 Pick-up
tomochikahara
@zetta1985
Agenda
Method Cascading
従来のMethod Chainへの批判
※ Method Chain != Fluent Interface
Method Cascadingでの解決
Method Cascadingの例
var tokai = (new StringBuffer("[")
..writeAll(["Aichi", "Gifu", "Mie"], ",") ..write("]")).toString();
query("#sample_text_id")
..text = "Click me!"
..onClick.listen(reverseText);
var person = (new PersonBuilder()..name = "to_hara"..age = 13).build();
Named / Factory
Constructor
Constructorの基本
class Person {
final bool isAdult;
Person(this.isAdult);
}
class Person {
final bool isAdult;
Person(int age) : this.isAdult = age >= 20;
}
class Person {
bool isAdult;
Person(int age) : this.isAdult = age >= 20 {
assert(age < 20 == !isAdult);
}
}
仮引数の定義とフィールドの初期化
フィールド初期化式リスト
(コンストラクタのリダイレクト含む)
オブジェクト初期化子
(finalフィールドへの初期化はできない)
Named Constructor
(名前付きコンストラクタ)
class Person {
final String name;
Person(this.name);
Person.copy(Person original) : this.name = original.name;
}
var hara = new Person("Hara");
var hara2 = new Person.copy(hara);
Factory Constructor
abstract class Person {
final int age;
Person._internal(this.age);
factory Person(int age) => age < 20 ? new Young(age) : new Adult(age);
}
class Young extends Person { Young(int age) : super._internal(age); }
class Adult extends Person { Adult(int age) : super._internal(age); }
Const Variable
変数のインライン展開
Const Constructor
class Location {
final String name;
const Location(this.name);
}
var l3 = const Location("Aichi");
var l4 = const Location("Aichi");
print( identical( l3, l4 ) ); // true
Implicit Interfaces
/ Mix-in
Implicit Interfaces
(暗黙的Interface)
class Person {
final bool isAdult;
Person(int age) : this.isAdult = age < 20;
}
class Young implements Person {
// getterのオーバーライド
bool get isAdult => false;
}
Mix-in Application
class Printable {
void printMe() => print(this.toString());
}
class Person extends Object with Printable {
final int age;
Person(this.age);
String toString() => "I'm $age years old.";
}
Implicit Interfaces & Mix - inの実用例
Dependency Injection : Cake Pattern
class Repository {
List<String> find() => ["data1", "data2"];
}
class Service {
Repository get repository => new Repository();
void execute() => print(repository.find());
}
class AwesomeRepository implements Repository {
List<String> find() => ["awesomeData1", "awesomeData2"];
}
abstract class AwesomeRepositoryModule {
Repository get repository => new AwesomeRepository();
}
typedef AwesomeService = Service with AwesomeRepositoryModule;