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
