Kotlin class property reference as a function

The following example t::xreturns a reference to the getter property. How to get the same for the 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 = ????
}
+9
source share
2 answers

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

val setter = t::x.setter
setter("abc")
+6
source

The return type t::xis KMutableProperty0<String>one that has a property setter, so you can do this:

val setter: (String) -> Unit = t::x.setter
setter("B")
println(getter()) // prints B now
+2
source

Source: https://habr.com/ru/post/1015858/


All Articles