Method reference to property setter

余生长醉 提交于 2021-02-04 18:59:26

问题


How could I get method reference to property setter without using kotlin-reflect?

Basically, if I'll write my code in java way it's super simple

fun setValue(i: Int) = Unit
val a: (Int) -> Unit = this::setValue

But for var value: Int I'm getting

var value = 1
val a: KMutableProperty0<Int> = this::value

回答1:


this::value is a property reference. It returns a KMutableProperty. To get the setter you will need the setter field of KMutableProperty. So you will need this:

class C {
    var field: Int = 1
    fun getFieldSetter(): (Int) -> Unit{
        return this::field.setter
    }
}



回答2:


Use this::value.setter in order to get the setter reference.




回答3:


Slightly shorter: just use this::value::set



来源:https://stackoverflow.com/questions/43933370/method-reference-to-property-setter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!