CodeBlanks Logo Icon CodeBlanks

KClass

Learn class info with ::class and KClass.

Class info with KClass

KClass holds the runtime info of a class. The ::class syntax gives you a KClass reference. It provides info about members, constructors and supertypes.

Example: val kc = String::class; println(kc.simpleName). This prints String. Use kc.isData to check if it is a data class and kc.members to list members. Reflection inspects types at runtime.

simpleName and isData

The simpleName property of KClass gives the short name of the class. Flags like isData, isAbstract and isSealed describe the class nature.

Example: data class User(val name: String). User::class.isData returns true. User::class.simpleName gives "User". These flags let you branch on the type structure at runtime.

Practice Print the Person class name

Define class Person(val name: String). In main print the result of Person::class.simpleName with println.

Starter code

Main.kt
// Person class: name property
// in main print the class name via reflection

Sample solution

Main.kt
class Person(val name: String)

fun main() {
    println(Person::class.simpleName)
}

Expected output

Person

Questions and answers

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

1 Which syntax gets a KClass reference of a class?

  • getClass()
  • .class
  • classOf<>()
  • ::class Correct answer

Explanation: In Kotlin ::class gives a KClass reference.

2 Complete the KClass reference

Question
val kc = String____
Answer
val kc = String::class

Explanation: ::class gives a KClass reference.

3 Match the KClass parts

Term Meaning
String::class KClass reference
simpleName Type name
isData Data class flag
members Members

All lessons in Advanced