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
46: Reified Generics in Practice
You've probably noticed by now that Kotlin's generics are great for compile-time safety, but they have a frustrating habit of disappearing the moment your code actually runs. This is type erasure. If you try to check if (item is T) inside a generic function, the compiler will stop you dead in its tracks because, at runtime, the JVM doesn't actually know what T is—it just sees Object.
The "Clunky" Class Parameter Approach
When I first encountered this, I did what most of us do: I started passing the class as an explicit argument. If I wanted a helper function to filter a list of mixed events down to one specific type, I'd write something like this:
fun <T : Any> filterEvents(events: List<BaseEvent>, clazz: KClass<T>): List<T> {
return events.filter { clazz.isInstance(it) }.map { it as T }
}
// Usage
val userEvents = filterEvents(allEvents, UserEvent::class)
This works. It's technically correct. But it's clunky. Every time I call this function, I'm repeating myself. I'm telling Kotlin I want a UserEvent via the generic type parameter, and then I'm telling it again by passing UserEvent::class. It feels like I'm fighting the language rather than using it.
Why the compiler hates is T
You might wonder why we can't just simplify that to if (it is T). The reason is that T is just a placeholder for the compiler. Once the code is compiled to bytecode, T is gone. If the JVM allowed is T, it would be lying to you; it would essentially be checking is Object, which is always true for any non-null value and would lead to a ClassCastException the second you tried to actually use the object.
Cleaning it up with reified
This is where reified comes in. By combining the inline keyword with reified, you're telling the compiler: "Don't just replace T with Object. Instead, take the actual type I used at the call site and bake it directly into the bytecode where this function is called."
Here is how I'd actually write that event filter today:
inline fun <reified T : BaseEvent> filterEvents(events: List<BaseEvent>): List<T> {
return events.filterIsInstance<T>()
// Or manually: events.filter { it is T }.map { it as T }
}
// Usage
val userEvents = filterEvents<UserEvent>(allEvents)
Notice the difference? The KClass argument is gone. The call site is cleaner. Because the function is inlined, the compiler knows exactly what T is at that specific point in the code and can generate a real instanceof check in the bytecode.
The "Hidden Cost" of Inlining
Now, I don't want you to just slap reified on every generic function you write. There's a trade-off here. Because inline functions copy the function's body directly into the call site, you can end up with "code bloat" if the function is large and called from hundreds of different places. You're essentially trading a bit of binary size for a lot of developer convenience and runtime performance (since you avoid the overhead of a function call and manual class reflections).
Another restriction: you can't use reified types in class definitions—only in functions. If you need a class to remember its type at runtime, you're stuck with the KClass parameter approach. But for utility methods, API wrappers, or dependency injection helpers, reified is an absolute lifesaver.
📋 Practical Task
Exercise: Building a Type-Safe JSON Mapper
Imagine you are building a network layer where the API returns a raw string, and you need to map it to a specific Data Transfer Object (DTO). Currently, the mapping function is clunky because it requires you to pass the KClass manually.
Your Task: Refactor the JsonMapper to use a reified generic function so that the user doesn't have to pass the class explicitly.
// The DTOs
data class User(val name: String)
data class Product(val sku: String)
object JsonMapper {
// NAIVE VERSION: Fix this!
fun <T : Any> mapResponse(json: String, clazz: kotlin.reflect.KClass<T>): T {
println("Parsing $json into ${clazz.simpleName}")
// Mocking the actual JSON parsing logic
return if (clazz == User::class) User("John Doe") as T
else Product("123-ABC") as T
}
}
fun main() {
val json = "{'id': 1}"
// This is the clunky way we want to avoid:
val user = JsonMapper.mapResponse(json, User::class)
// TODO: Implement and call the reified version here so it looks like:
// val user = JsonMapper.mapResponse<User>(json)
}
Requirements:
- Modify
mapResponseto beinline. - Make the type parameter
Treified. - Remove the
clazz: KClass<T>parameter. - Update the internal logic to use
T::classinstead of the passedclazz.
There are no comments for now.