Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = ????
}
like image 633
David Soroko Avatar asked Mar 18 '17 12:03

David Soroko


People also ask

How do you call getter and setter methods in Kotlin?

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.

What is the use of get () in Kotlin?

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'.

How do you get to the getter in Kotlin?

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.

What is accessors in Kotlin?

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.


Video Answer


2 Answers

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

val setter = t::x.setter
setter("abc")
like image 171
hotkey Avatar answered Sep 29 '22 05:09

hotkey


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
like image 20
zsmb13 Avatar answered Sep 29 '22 06:09

zsmb13