Delegate property to another property

Viewed 2640

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

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

2 Answers
Related