Delegate property to another property

前端 未结 2 978
孤城傲影
孤城傲影 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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(val delegate: KMutableProperty0) {
        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.

提交回复
热议问题