kotlinkotlin-reflect

Reference to Kotlin class property setter as function


In the example below, t::x returns a reference to a property getter. How do I obtain the same for a setter?

class Test(var x: String) {}

fun main(args: Array<String>) {
    val t = Test("A")

    val getter: () -> String = t::x
    println(getter()) // prints A

    val setter: (String) -> Unit = ????
}

Solution

  • Use t::x.setter, it returns a MutableProperty0.Setter<T>, which can be used as a function:

    val setter = t::x.setter
    setter("abc")