Delegate property to another property

前端 未结 2 979
孤城傲影
孤城傲影 2021-01-17 12:49

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

class SettingsPage {
  lateinit var tagCharacters: JTextField
  lateini         


        
相关标签:
2条回答
  • 2021-01-17 13:16

    UPD: Since Kotlin 1.4, the standard library includes the necessary extensions that 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
    

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

    And the usage:

    class Container(var x: Int)
    
    class Foo {
        var container = Container(1)
        var x by Alias(container::x)
    }
    

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

    0 讨论(0)
  • 2021-01-17 13:16

    Follow-up, if you would like to see support for property references in Kotlin, please vote and track this issue for updates: https://youtrack.jetbrains.com/issue/KT-8658

    0 讨论(0)
提交回复
热议问题