问题
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