Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method reference to property setter

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
like image 451
Stepango Avatar asked Feb 04 '23 11:02

Stepango


2 Answers

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
    }
}
like image 178
glee8e Avatar answered Feb 08 '23 16:02

glee8e


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

like image 32
mrlem Avatar answered Feb 08 '23 14:02

mrlem