4

Get property information from delegated property outside the getValue () and set...

 2 years ago
source link: https://www.codesd.com/item/get-property-information-from-delegated-property-outside-the-getvalue-and-setvalue-functions.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Get property information from delegated property outside the getValue () and setValue () functions

advertisements

I'm trying to implement the JavaFX Property interface with a delegated Kotlin property, so that it can be used like so:

class Foo(bar:Bar){
    val barProperty=PropertyFX(bar)
    var bar by barProperty
}

I wrote up a small class for this that works (mostly):

class PropertyFX<T>(value:T):SimpleObjectProperty<T>(value),ReadWriteProperty<Any?,T>{
    override fun getValue(thisRef:Any?,property:KProperty<*>)=get()
    override fun setValue(thisRef:Any?,property:KProperty<*>,value:T)=set(value)
}

However, this class doesn't implement the interface's getBean() and getName() methods. They should return the values thisRef and property.name, respectively, from the arguments referenced in the getValue() and setValue() functions, but I don't have access to those arguments from outside the functions.

I could store the values the first time they're used, like so:

class PropertyFX<T>(value:T):SimpleObjectProperty<T>(value),ReadWriteProperty<Any?,T>{
    private var bean:Any?=null
    private var name=""
    override fun getBean()=bean
    override fun getName()=name
    override fun getValue(thisRef:Any?,property:KProperty<*>):T{
        bean=thisRef
        name=property.name
        return get()
    }
    override fun setValue(thisRef:Any?,property:KProperty<*>,value:T){
        bean=thisRef
        name=property.name
        set(value)
    }

But this seems like an awful hack, and it doesn't return the correct values for getBean() and getName() until the property is accessed once. Is there a way to get these values earlier without passing them into the constructor, like is required by SimpleObjectProperty?


In Kotlin 1.1 (since 1.1-M04), you can use the provideDelegate operator convention to define a function which will be called once when the instance of the delegate is created. In your example, you can declare provideDelegate in PropertyFX and return a new delegate with the information about the container and the property. More info: https://blog.jetbrains.com/kotlin/2016/12/kotlin-1-1-m04-is-here/#provide-delegate


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK