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
