我有许多遵循这种模式的属性,基本上从下面的模板中改变的唯一内容是:
var foo: Double = 0.0
get() {
update()
return field
}
var foo2: Double = 1.23
get() {
update()
return field
}
有什么方法可以使用委托来简化(减少代码的详细程度)?
答案 0 :(得分:1)
不确定
private fun <T> publishingDelegate(value: T): ReadWriteProperty<Any?, T> = object: ReadWriteProperty<Any?, T> {
private var initValue = value
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
update()
return initValue
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
update()
initValue = value
}
}
var foo: Double by publishingDelegate(0.0)
var foo2: Double by publishingDelegate(1.23)