Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
106: KClass and Runtime Type Information
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
AppEventand three subclasses:UserLogin,UserLogout, andSystemError. - Create a function
logEvent(event: AppEvent). - Inside
logEvent, useevent::classto retrieve thesimpleNameof 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.
There are no comments for now.