CodeBlanks Logo Icon CodeBlanks

Summary - Reflection

Combine KClass, KProperty and call to write a serialization framework.

Summary - Reflection

In this group you saw the reflection tools: class info with KClass, property access with KProperty, function info with KFunction, dynamic calling with call and metadata with annotations.

This lesson includes a small task that combines three of them: you will take a class's KClass reference and print its simpleName and members.size. This pattern brings together the foundation of reflection.

Practice Summary: inspect Person KClass

Define class Person(val name: String, val age: Int). In main take val kc = Person::class and write first println(kc.simpleName), then println(kc.members.size).

Starter code

Main.kt
// Person class: name and age properties
// in main take kc, print its name and member count

Sample solution

Main.kt
class Person(val name: String, val age: Int)

fun main() {
    val kc = Person::class
    println(kc.simpleName)
    println(kc.members.size)
}

Expected output

Person
5

Questions and answers

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

1 Which method calls a function at runtime?

  • call Correct answer
  • let
  • apply
  • also

Explanation: call invokes a KFunction.

2 Match the reflection tools

Term Meaning
KClass Class info
KProperty Property access
KFunction Function info
annotations Metadata

3 Complete the simpleName call

Question
val kc = Person::class
println(kc.____)
Answer
val kc = Person::class
println(kc.simpleName)

Explanation: kc.simpleName gives the class name.

All lessons in Advanced