您可以将房产委托给Kotlin的另一处房产吗?我有以下代码:
class SettingsPage {
lateinit var tagCharacters: JTextField
lateinit var tagForegroundColorChooser: ColorPanel
lateinit var tagBackgroundColorChooser: ColorPanel
var allowedChars: String
get() = tagCharacters.text
set(value) = tagCharacters.setText(value)
var tagForegroundColor by tagForegroundColorChooser
var tagBackgroundColor by tagBackgroundColorChooser
}
为了获得属性委托,我声明了以下两个扩展函数:
operator fun ColorPanel.getValue(a: SettingsPage, p: KProperty<*>) = selectedColor
operator fun ColorPanel.setValue(a: SettingsPage, p: KProperty<*>, c: Color?) { selectedColor = c }
但是,我想写的内容如下:
class SettingsPage {
lateinit var tagCharacters: JTextField
lateinit var tagForegroundColorChooser: ColorPanel
lateinit var tagBackgroundColorChooser: ColorPanel
var allowedChars: String by Alias(tagCharacters.text)
var tagForegroundColor by Alias(tagForegroundColorChooser.selectedColor)
var tagBackgroundColor by Alias(tagBackgroundColorChooser.selectedColor)
}
这可以做Kotlin吗?我如何写课Alias
?
答案 0 :(得分:12)
是的,它是可能的:您可以使用bound callable reference作为存储在别名中的属性,然后Alias
实现将如下所示:
class Alias<T>(val delegate: KMutableProperty0<T>) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): T =
delegate.get()
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
delegate.set(value)
}
}
用法:
class Container(var x: Int)
class Foo {
var container = Container(1)
var x by Alias(container::x)
}
要引用同一实例的属性,请使用this::someProperty
。
答案 1 :(得分:0)
跟进,如果您希望在Kotlin看到对财产参考的支持,请投票并跟踪此问题以获取更新:https://youtrack.jetbrains.com/issue/KT-8658