「特別な」振る舞いを持つすべての種類のプロパティは、delegated propertiesで処理されます。
すべての機能要求はthe official Kotlin issue trackerにする必要があります。実際には、あなたが提案したものに対してすでにKT-7180というリクエストがあります。ここで
は(問題の)可能な実装である:ここでは
class InitOnceVar<T>() : ReadWriteProperty<Any?, T> {
private var initialized = false
private var value: T? = null
override fun get(thisRef: Any?, desc: PropertyMetadata): T {
if (!initialized) throw IllegalStateException("Property ${desc.name} should be initialized before get")
return value
}
override fun set(thisRef: Any?, desc: PropertyMetadata, value: T) {
if (initialized) throw IllegalStateException("Property ${desc.name} could be initialized only once")
this.value = value
initialized = false
}
}
は、あなたがそれを使用する方法です:のみ、この問題の
var x: String by InitOnceVar()
x = "star"
x = "stop" //Exception
作品... –