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 = ????
}
When you instantiate object of the Person class and initialize the name property, it is passed to the setters parameter value and sets field to value . Now, when you access name property of the object, you will get field because of the code get() = field . This is how getters and setters work by default.
In Kotlin, setter is used to set the value of any variable and getter is used to get the value. Getters and Setters are auto-generated in the code. Let's define a property 'name', in a class, 'Company'.
Getter in kotlin is by default public, but you can set the setter to private and set the value by using one method inside a class. Like this. Show activity on this post.
1.0. interface Accessor<out V> Represents a property accessor, which is a get or set method declared alongside the property. See the Kotlin language documentation for more information.
Use t::x.setter
, it returns a MutableProperty0.Setter<T>
, which can be used as a function:
val setter = t::x.setter
setter("abc")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With