concept get in category kotlin

appears as: get
Kotlin in Action

This is an excerpt from Manning's book Kotlin in Action.

Another nice trick used in listing 2.24 is the shorthand syntax for getting and updating the values of a map by key. Instead of calling get and put, you can use map[key] to read values and map[key] = value to set them. The code

Figure 7.6. Access via square brackets is transformed into a get function call.

You specify the element to be annotated with a use-site target declaration. The use-site target is placed between the @ sign and the annotation name and is separated from the name with a colon. The word get in figure 10.1 causes the annotation @Rule to be applied to the property getter.

You can invoke the call method on a KProperty instance as well, and it will call the getter of the property. But the property interface gives you a better way to obtain the property value: the get method.

To access the get method, you need to use the correct interface for the property, depending on how it’s declared. Top-level properties are represented by instances of the KProperty0 interface, which has a no-argument get method:

var counter = 0 >>> val kProperty = ::counter >>> kProperty.setter.call(21)    #1 >>> println(kProperty.get())    #2 21 #1 - Calls a setter through reflection, passing 21 as an argument #2 - Obtains a property value by calling “get”

A member property is represented by an instance of KProperty1, which has a one-argument get method. To access its value, you must provide the object instance for which you need the value. The following example stores a reference to the property in a memberProperty variable; then you call memberProperty.get(person) to obtain the value of this property for the specific person instance. So if a memberProperty refers to the age property of the Person class, memberProperty.get(person) is a way to dynamically get the value of person.age:

class Person(val name: String, val age: Int)

>>> val person = Person("Alice", 29)
>>> val memberProperty = Person::age
>>> println(memberProperty.get(person))
29

Note that KProperty1 is a generic class. The memberProperty variable has the type KProperty<Person, Int>, where the first type parameter denotes the type of the receiver and the second type parameter stands for the property type. Thus you can call its get method only with a receiver of the right type; the call member-Property.get("Alice") won’t compile.