name; private final int price; private final Country country; public Fruit(final String name, final int price, final Country country) { this.name = name; this.price = price; this.country = country; } public String getName() { return name; } public int getPrice() { return price; } public Country getCountry() { return country; } public Fruit withName(final String name) { return new Fruit(name, price, country); } public Fruit withPrice(final int price) { return new Fruit(name, price, country); } public Fruit withCountry(final Country country) { return new Fruit(name, price, country); } // toStringとか // equalsとか // hashCodeとか public static Builder builder() { return new Builder(); } public static class Builder { private String name; private int price; private Country country; public Fruit build() { return new Fruit(name, price, country); } public Builder name(final String name) { this.name = name; return this; } public Builder price(final int price) { this.price = price; return this; } public Builder country(final Country country) { this.country = country; return this; } • データを表現するクラス • イミュータブルにしたい • private final フィールド • コンストラクタ • getter • toString, equals, hashCode • Builderクラス (Lombokライクな) Fruitクラス
value fun getValue(): Long = _value override fun toString(): String = "Id($_value)" } val id = Id(123) id.getValue() //=> 123 id.toString() //=> "Id(123)"
value fun getValue(): Long = _value override fun toString(): String = "Id($_value)" } val id = Id(123) id.getValue() //=> 123 id.toString() //=> "Id(123)" コンストラクタ インスタンス生成
value fun getValue(): Long = _value override fun toString(): String = "Id($_value)" } val id = Id(123) id.getValue() //=> 123 id.toString() //=> "Id(123)" 値を保持し、 getterを提供 メソッド呼び出し デフォルトは public
value fun getValue(): Long = _value override fun toString(): String = "Id($_value)" } val id = Id(123) id.getValue() //=> 123 id.toString() //=> "Id(123)" toStringを オーバライド 式展開
= initial operator fun getValue(thisRef: Any, prop: KProperty<*>): T { return value } operator fun setValue(thisRef: Any, prop: KProperty<*>, value: T) { this.value = value } } class User(name: String) { var name: String by MyProp(name) }