Skip to Content
Course content

46: Reified Generics in Practice

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

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 mapResponse to be inline.
  • Make the type parameter T reified.
  • Remove the clazz: KClass<T> parameter.
  • Update the internal logic to use T::class instead of the passed clazz.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.