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
30: Inline Functions and Reified Types
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
ServiceRegistrythat holds aMutableMap<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
inlinefunction calledgetService<reified T : Any>(). This function should look up the service in the map and return it cast as typeT. - 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()There are no comments for now.