Reputation: 9096
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 = ????
}
Upvotes: 16
Views: 4783
Reputation: 5421
t::x::set
This works without kotlin-reflect
because it doesn't call any external methods, unlike t::x.setter
Still, the cleanest code is generated when using lambda syntax.
Upvotes: 6
Reputation: 148139
Use t::x.setter
, it returns a MutableProperty0.Setter<T>
, which can be used as a function:
val setter = t::x.setter
setter("abc")
Upvotes: 14
Reputation: 89638
The return type of t::x
is KMutableProperty0<String>
, which has a setter
property, so you can do this:
val setter: (String) -> Unit = t::x.setter
setter("B")
println(getter()) // prints B now
Upvotes: 6