Skip to Content
Course content

106: KClass and Runtime Type Information

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Wait, what is a KClass and how is it different from a Java Class?

If you've spent any time in the JVM ecosystem, you're probably used to java.lang.Class. In Kotlin, we have KClass. Think of KClass as the Kotlin-native representation of a class. It's designed to understand Kotlin-specific features that Java just doesn't know about—like nullability, properties (versus just fields), and data classes.

When you write MyClass::class, you're getting a KClass. If you're working with a library that was written in Java and it specifically asks for a java.lang.Class, you can't just pass the KClass directly. You'll need to bridge the gap using the .java extension property:

val kotlinClass = UserProfile::class        // This is a KClass<UserProfile>
val javaClass = UserProfile::class.java     // This is a java.lang.Class<UserProfile>

I usually stick with KClass whenever possible because it gives me access to the kotlin-reflect library, which is far more powerful for inspecting Kotlin code than the standard Java reflection API.

How do I get the class of an object if I don't know the type at compile time?

This is where runtime type information (RTTI) becomes actually useful. Let's say you're building a plugin system where you receive a generic Any object, and you need to figure out what it is to handle it correctly. You can use the ::class syntax on the instance itself.

Check out this example. Imagine we have different types of payment methods, and we need to log the specific type being used:

sealed class PaymentMethod
class CreditCard(val number: String) : PaymentMethod()
class PayPal(val email: String) : PaymentMethod()

fun processPayment(method: PaymentMethod) {
    val runtimeClass = method::class 
    println("Processing payment using: ${runtimeClass.simpleName}")
    
    if (runtimeClass == CreditCard::class) {
        println("Applying credit card processing fees...")
    }
}

In this snippet, method::class looks at the actual object on the heap at runtime and says, "Oh, this is actually a CreditCard," even though the function signature only knows it's a PaymentMethod.

Can I use KClass to actually do things, like instantiate objects dynamically?

Yes, but there's a catch. To do a lot of the "cool" stuff with KClass—like listing all functions, checking for annotations, or calling createInstance()—you need to add the kotlin-reflect dependency to your project. Without it, KClass is pretty lean to keep the binary size small.

Once you have the reflection library, you can do things that feel almost like magic. For example, if you have a class with a no-argument constructor, you can spin up an instance just from the class reference:

import kotlin.reflect.full.createInstance

class ReportGenerator {
    fun generate() = println("Generating report...")
}

val kClass = ReportGenerator::class
val instance = kClass.createInstance() // Dynamically creates a ReportGenerator object
instance.generate()

I'll be honest: use this sparingly. Reflection is slower than direct calls and it bypasses some of the compile-time safety that makes Kotlin great. If you find yourself using createInstance() everywhere, you probably actually need a Factory pattern or Dependency Injection.




📋 Practical Task

Build a Runtime Type-Based Event Logger

Your task is to create a system that logs events based on their runtime type without using a when block or if (is) checks. Instead, you will use the KClass of the event to determine the log prefix.

Requirements:

  • Create a sealed class AppEvent and three subclasses: UserLogin, UserLogout, and SystemError.
  • Create a function logEvent(event: AppEvent).
  • Inside logEvent, use event::class to retrieve the simpleName of the class.
  • Print a message in the format: "[EVENT: ClassName] Event occurred at [Current Time]".
  • Test your function by passing instances of all three event types into it.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.