将财产委托给另一个财产 [英] Delegate property to another property

查看:77
本文介绍了将财产委托给另一个财产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以将一个财产委派给科特林的另一个财产吗?我有以下代码:

Can you delegate a property to another property in Kotlin? I have the following code:

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
}

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

In order to get property delegation, I declare the following two extension functions:

  operator fun ColorPanel.getValue(a: SettingsPage, p: KProperty<*>) = selectedColor
  operator fun ColorPanel.setValue(a: SettingsPage, p: KProperty<*>, c: Color?) { selectedColor = c }

但是,我想写的是如下内容:

However, what I would like to write is something like the following:

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)
}

这有可能做科特林吗?如何编写类Alias?

Is this possible to do Kotlin? How do I write the class Alias?

推荐答案

是的,有可能:您可以使用

Yes, it's possible: you can use a bound callable reference for a property that you store in the alias, and then the Alias implementation will looks like this:

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.

To reference a property of the same instance, use this::someProperty.

这篇关于将财产委托给另一个财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆