この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
はじめに
毎日Kotlinシリーズです。
このシリーズを初めての方はこちらです。「毎日Kotlin」はじめました | Developers.IO
問題
今日から新章突入!
Read about properties in Kotlin.
Add a custom setter to PropertyExample.propertyWithCounter so that the counter property is incremented every time propertyWithCounter is assigned to.
class PropertyExample() {
var counter = 0
var propertyWithCounter: Int? = null
set
}
狙い
ここで考えて欲しい問題の意図はなんだろうか?
Kotlinでは、getter,setterが勝手に作られます。カスタマイズしたいときが多々あります。今回はsetterをカスタマイズしてみましょう。
解答例
class PropertyExample() {
var counter = 0
var propertyWithCounter: Int? = null
set(v: Int?) {
field = v
counter++
}
}
getter/setterの詳しい資料はこちらを参照。
Properties and Fields: Getters, Setters, const, lateinit - Kotlin Programming Language
気をつけておきたいのは、setterです。
setterの場合は、セットされた値が引数で取得できますが、(今回の場合はset(v: Int?))このままでは、propertyWithCounterに保存されません。保存が必要な場合はfield = vのようにfiledに保存したい値をセットしないといけません。filedはその変数自身のことを指しています。無限ループにならないように、filedにセットしても再度setterが呼ばれることはありません。
上記をJavaに戻してみると
public final class PropertyExample {
private int counter;
@Nullable
private Integer propertyWithCounter;
public final int getCounter() {
return this.counter;
}
public final void setCounter(int var1) {
this.counter = var1;
}
@Nullable
public final Integer getPropertyWithCounter() {
return this.propertyWithCounter;
}
public final void setPropertyWithCounter(@Nullable Integer v) {
this.propertyWithCounter = v;
int var2 = this.counter++;
}
}
setter部分が以下のようになっていますね。
public final void setPropertyWithCounter(@Nullable Integer v) {
this.propertyWithCounter = v;
int var2 = this.counter++;
}
this.propertyWithCounterのところがfiledに相当しています。
あとがき
Day35.でまたお会いしましょう。