CodeBlanks Logo Icon CodeBlanks

KProperty

Learn property info with KProperty.

Property info with KProperty

KProperty holds a reference to a property. It is obtained with ::propertyName. name gives the property name; get(instance) gives the value.

Example: class User(val name: String). val prop = User::name. prop.name returns "name". prop.get(User("Alex")) gives "Alex". This pattern reads property values at runtime.

Reading values with get

KProperty.get(instance) reads a property value. For class properties the instance is required; for top-level properties it is not.

Example: val u = User("Alex"); val v = User::name.get(u). This returns "Alex". get provides dynamic access at runtime; it is slower than compile-time access but flexible.

Practice Read a User property

Define class User(val name: String). In main create val u = User("Alex"), get the reference val prop = User::name and call println(prop.get(u)).

Starter code

Main.kt
// User class: name property
// in main create u, get prop reference, print its value

Sample solution

Main.kt
class User(val name: String)

fun main() {
    val u = User("Alex")
    val prop = User::name
    println(prop.get(u))
}

Expected output

Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the KProperty reference

Question
class User(val name: String)
val prop = User____
Answer
class User(val name: String)
val prop = User::name

Explanation: ::name gives a KProperty reference.

2 Which method reads a class property value via KProperty?

Main.kt
KProperty.get(instance) gives the value.
  • get(instance) Correct answer
  • call()
  • invoke()
  • apply()

Explanation: get(instance) gives the property value.

3 Match the KProperty parts

Term Meaning
User::name Property reference
prop.name Property name
prop.get(u) Value read
val u = User(...) Instance

All lessons in Advanced