Is there any other way to use property as delegate...
# announcements
i
Is there any other way to use property as delegate for another property?
Copy code
class Container {
    val view: View2 = View2()
    var onClickListener:(() -> Unit)? by view.onClickListener // does not work
}

class View2 {
    var onClickListener:(() -> Unit)? = null
}
v
Custom getter and setter?
Copy code
class Container {
    val view: View2 = View2()
    var onClickListener:(() -> Unit)? 
        get() = view.onClickListener
        set(onClickListener) {
            view.onClickListener = onClickListener
        }
}
class View2 {
    var onClickListener:(() -> Unit)? = null
}
i
I was hoping to avoid these setters and getters
If language does not support this maybe it’s possible to write a custom Delegate 🤔
Copy code
class Container {
    val view: View2 = View2()
    var onClickListener:(() -> Unit)? by PropertyDelegate(view.onClickListener)
}
OK found it 😄
Copy code
class Container {
    val view: View2 = View2()
    var onClickListener: (() -> Unit)? by Alias(view::onClickListener)
}

class View2 {
    var onClickListener:(() -> Unit)? = null
}

class Alias<T>(private 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)
    }
}
v
Ah, wait, I'm stupid, you can just use the KProperty
Copy code
class Container {
    val view: View2 = View2()
    var onClickListener:(() -> Unit)? by view::onClickListener
}
class View2 {
    var onClickListener:(() -> Unit)? = null
}
In your inital version you tried to delegate to the properties value instead of to the property
i
Indeed - thx this is what I wanted :-D
I think this “property delegation” behaviour was introduced just recently in Kotlin 1.4
v
I wouldn't say recently, but yes 🙂
In 1.4.0, we have added new features to improve your experience with delegated properties in Kotlin:
- Now a property can be delegated to another property.