liveBook · Manning

Get method

As explained in Kotlin in Action, 2E

The get method on a Kotlin property reference obtains the referenced property's value from a receiver object.

The get method on a Kotlin property reference reads the referenced property's value from a receiver object. For a member reference such as Person::age, pass the Person instance to get. section 12.2.1 section 12.2.2

Reading a member property

class Person(val name: String, val age: Int) fun main() { val person = Person("Alice", 29) val memberProperty = Person::age println(memberProperty.get(person)) // 29 } Here, Person::age is a KProperty1<Person, Int>. Its get method accepts the Person receiver and returns that object's age. section 12.2.1

The method becomes especially useful when properties are discovered dynamically:

  • memberProperties produces property references for a class, including inherited non-extension properties. section 12.2.1
  • A dynamically enumerated property has type KProperty1<Any, *>; prop.get(obj) therefore returns Any? and cannot provide compile-time receiver checks. section 12.2.2
  • Passing the same object used to obtain the properties keeps the reflective receiver correct. section 12.2.2
class Person(val name: String, val age: Int)

fun main() {
   val person = Person("Alice", 29)
   val memberProperty = Person::age
   println(memberProperty.get(person))
   // 29
}

Shows the smallest runnable example of calling get on Person::age with a receiver object. section 12.2.1

Listing 12.1 Serializing an object
private fun StringBuilder.serializeObject(obj: Any) {
    val kClass = obj::class as KClass<Any>              #1
    val properties = kClass.memberProperties            #2
 
    properties.joinToStringBuilder(
        this, prefix = "{", postfix = "}") { prop ->
        serializeString(prop.name)                      #3
        append(": ")
        serializePropertyValue(prop.get(obj))           #4
    }
}

Shows get applied while serializing every property discovered through Kotlin reflection. section 12.2.2

How Kotlin in Action, 2E covers it

How deep it goes
Explains typed and dynamically discovered property access, stopping short of implementation internals for getters.
Examples
Uses Person::age to return 29 and prop.get(obj) to retrieve values while producing serialized object output.
What it assumes
Assumes Kotlin property references and receiver objects; demonstrates reflective discovery through KClass and memberProperties.
What you can do after
Apply it via Kotlin reflection to read a known member property or serialize values discovered at runtime.
How it connects
Connects property references with KProperty1, memberProperties, KClass, Kotlin reflection, and object serialization.

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.