KProperty is Kotlin’s run-time representation of a property declaration. It exposes property metadata such as name and annotations, and it can read a property value dynamically. It belongs to the reflection hierarchy: KProperty extends KCallable, so it also supports the general call operation, although get is the clearer property-specific API. section 12.2.1 section 12.3
class Person(val name: String, val age: Int)
fun main() {
val person = Person("Alice", 29)
val memberProperty = Person::age
println(memberProperty.get(person))
// 29
}
A member reference such as Person::age produces a KProperty1 whose get method needs the receiver object. The type parameters preserve both the receiver type and the property value type, so get accepts the right kind of instance. section 12.2.1
Choose the property interface by receiver count and mutability. KProperty0 represents a top-level read-only property and has no-argument get; KProperty1 represents a member property and requires its receiver. KMutableProperty0 and KMutableProperty1 add set for changing values. When properties are enumerated dynamically, their exact value type may be unknown, commonly yielding KProperty1<Any, *> and an Any? result. section 12.2.1 section 12.3 section 12.2.2
KProperty supports two practical reflection tasks:
- Read values from property references or from a class’s memberProperties collection with get. section 12.2.1 section 12.2.2
- Inspect run-time annotations through annotations or findAnnotation, then adapt behavior such as excluding a field, renaming a JSON key, or selecting a custom serializer. section 12.2.3
- Receive a delegated property’s declaration in operator getValue and setValue, using prop.name rather than storing a duplicate property name. section 9.5.3
Listing 12.3 Serializing a single property
private fun StringBuilder.serializeProperty(
prop: KProperty1<Any, *>, obj: Any
) {
val jsonNameAnn = prop.findAnnotation<JsonName>()
val propName = jsonNameAnn?.name ?: prop.name
serializeString(propName)
append(": ")
serializePropertyValue(prop.get(obj))
}
Serialization combines metadata and value access: a KProperty1 is checked for JsonName, its reflected name is chosen as the JSON key, and get(obj) supplies the value. The wildcard value type accommodates properties discovered at run time. section 12.2.3 section 12.2.2
Delegates receive KProperty<*> as the prop parameter whenever Kotlin calls their operator functions. That makes the same delegate reusable for several properties while still reporting which property changed. The standard Delegates.observable follows this pattern by passing a KProperty to its change callback. section 9.5.3
