liveBook · Manning

KProperty1

As explained in Kotlin in Action, 2E

KProperty1 is a Kotlin reflection interface for a property whose getter takes one receiver object of a specified type.

KProperty1 represents a Kotlin member property whose getter requires one receiver object. Its two type parameters identify the receiver and property value, such as KProperty1<Person, Int> for Person::age. section 12.2.1

Reading a member property

class Person(val name: String, val age: Int) val person = Person("Alice", 29) val memberProperty = Person::age println(memberProperty.get(person)) // 29 The get call supplies the Person receiver and returns that instance's age. Passing a value of another type, such as "Alice", fails at compile time when the reference is typed as KProperty1<Person, Int>. section 12.2.1

KProperty1 is useful when code must inspect or read class properties dynamically. Enumerating memberProperties commonly widens the type to KProperty1<Any, *>; get then returns Any?, so compile-time receiver checks are lost. Passing the same object used to obtain the properties keeps the 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
}

Use this compact listing to see a KProperty1 reference, its receiver argument, and the resulting property value. 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
    }
}

This serializer listing shows KProperty1 used with memberProperties to obtain names and values dynamically. section 12.2.2

How Kotlin in Action, 2E covers it

How deep it goes
Explains generic receiver and value types, compile-time checking, dynamic enumeration, and widened Any? access.
Examples
Uses Person::age for typed access and memberProperties inside a reflection-based JSON serializer.
What you can do after
Apply it via Kotlin reflection to read typed member properties or serialize enumerated object properties.
How it connects
Connects KProperty1 with KProperty, KMutableProperty1, KCallable, KClass, memberProperties, and object serialization.

Related concepts

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.