gpt4 book ai didi

kotlin - 将属性委托(delegate)给另一个属性

转载 作者:IT老高 更新时间:2023-10-28 13:41:18 25 4
gpt4 key购买 nike

你可以将一个属性委托(delegate)给 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
}

为了获得属性委托(delegate),我声明了以下两个扩展函数:

  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类怎么写?

最佳答案

UPD: 从 Kotlin 1.4 开始,标准库包括必要的扩展,allow this out of the box :

class MyClass(var memberInt: Int, val anotherClassInstance: ClassWithDelegate) {
var delegatedToMember: Int by this::memberInt
var delegatedToTopLevel: Int by ::topLevelInt

val delegatedToAnotherClass: Int by anotherClassInstance::anotherClassInt
}
var MyClass.extDelegated: Int by ::topLevelInt

是的,有可能:您可以使用 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

关于kotlin - 将属性委托(delegate)给另一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45074596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com