Skip to Content
Course content

30: Inline Functions and Reified Types

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

I’ve been thinking about how we handle generics in Kotlin. Most of the time, they work beautifully, but there's this one recurring frustration I hit whenever I'm writing utility functions—specifically when I need to know exactly what type is being passed in at runtime. Let's look at a scenario where this usually breaks.

Trying to peek at the type

Imagine we're building a small network layer. I want a helper function that takes a JSON string and converts it into an object of type T. While I'm at it, I want to log the name of that type just for debugging purposes. Here is my first attempt:

fun <T> parseResponse(json: String): T {
    println("Parsing response as type: ${T::class.simpleName}") 
    // Imagine some JSON parsing logic here
    return someParser.decode(json) 
}

The second I write T::class, the IDE turns red. The compiler tells me that "Cannot use 'T' as reified type parameter." This is a classic JVM headache called Type Erasure. Basically, generics only exist for the compiler to keep us safe while writing code; once the code is compiled to bytecode, the T disappears and becomes a generic Object. At runtime, the function has no idea if T was a User, a Product, or a List<String>.

The boilerplate tax

The standard "textbook" fix for this is to pass the class as an explicit argument. It's a common pattern in libraries like Gson or Jackson. Let's try that:

fun <T : Any> parseResponse(json: String, clazz: KClass<T>): T {
    println("Parsing response as type: ${clazz.simpleName}")
    return someParser.decode(json, clazz)
}

// Now, calling it looks like this:
val user = parseResponse("<json>", User::class)

It works, but I hate it. It feels redundant. I'm already specifying the type in the function call (or letting Kotlin infer it), so why do I have to pass User::class as a second argument? It's extra noise that doesn't add value to the API. I want the call site to be clean: parseResponse<User>("<json>").

Letting the compiler do the heavy lifting

This is where inline and reified come in. If I mark the function as inline, the Kotlin compiler doesn't actually "call" the function in the traditional sense. Instead, it literally copies the bytecode of the function body and pastes it directly into the place where I called it.

Because the code is pasted at the call site, the compiler knows exactly what T is at that specific moment. We can then use the reified keyword to tell Kotlin, "Hey, keep this type information available at runtime." Watch what happens to our parser:

inline fun <reified T : Any> parseResponse(json: String): T {
    println("Parsing response as type: ${T::class.simpleName}")
    return someParser.decode(json, T::class)
}

// Now the call is clean again!
val user = parseResponse<User>("<json>")

Suddenly, T::class is valid. Why? Because if I call this for a User, the compiler replaces the inline block with the actual User class. It's not "searching" for the type at runtime; the type is hard-coded into the bytecode at the call site.

A word of caution on performance

You might be tempted to make every generic function inline now. Don't. Since inline copies the function body everywhere it's used, if you have a massive function that you call in 100 different places, your compiled binary size will bloat.

Use inline when you are taking a lambda as a parameter (to avoid creating anonymous class objects) or when you absolutely need reified types. In our parser example, the function body is tiny, so the trade-off is a no-brainer: we get a much cleaner API with virtually no performance penalty.




📋 Practical Task

Build a Type-Safe Dependency Registry

You are building a simple Service Locator/Dependency Registry. You want to be able to retrieve services from a map without having to pass the class reference manually every time.

Requirements:

  • Create a class ServiceRegistry that holds a MutableMap<KClass<*>, Any>.
  • Implement a register<T : Any>(service: T) method that adds the service to the map using its class as the key.
  • Implement an inline function called getService<reified T : Any>(). This function should look up the service in the map and return it cast as type T.
  • If the service is not found, return null.

Test your implementation:

class DatabaseService { fun connect() = println("DB Connected") }
class ApiService { fun fetch() = println("API Fetched") }

val registry = ServiceRegistry()
registry.register(DatabaseService())
registry.register(ApiService())

// This should return the DatabaseService instance without needing DatabaseService::class
val db = registry.getService<DatabaseService>()
db?.connect()
Rating
0 0

There are no comments for now.

to be the first to leave a comment.