DEV Community

Cover image for Advanced Kotlin: Inline Reified Generics for Type-Safe Reflection and JSON Parsing
Den B
Den B

Posted on

Advanced Kotlin: Inline Reified Generics for Type-Safe Reflection and JSON Parsing

One of the most powerful yet underused features in Kotlin is the combination of inline + reified type parameters. This allows you to retain type information at runtime, enabling type-safe operations like JSON deserialization, dependency resolution, and reflection—without needing explicit Class objects.

Real-World Problem: Generic JSON Parsing

In Java/Kotlin with Gson or Moshi:

inline fun <reified T> Gson.fromJson(json: String): T =
    this.fromJson(json, object : TypeToken<T>() {}.type)
Enter fullscreen mode Exit fullscreen mode

🔍 Without reified, you’d have to pass Class explicitly, and lose type safety for generic types like List.

💡 Use Case: DSL or DI Framework

Suppose you’re writing a lightweight DI container or DSL:

inline fun <reified T> inject(): T {
    return container.resolve(T::class.java) as T
}
Enter fullscreen mode Exit fullscreen mode

✅ No need to pass User::class.java — it’s inferred and reified at compile time.

🔥 Use Case: Type-Safe Routing or Serialization

inline fun <reified T> isTypeOf(value: Any): Boolean {
    return value is T
}

val result = isTypeOf<String>("test") // ✅ true
val result2 = isTypeOf<List<Int>>(listOf(1, 2, 3)) // ✅ true
Enter fullscreen mode Exit fullscreen mode

📌 Notes for Quick Reference
• Use inline + reified when you want access to T::class, is T, or TypeToken().
• Great for JSON parsing, reflection utilities, and type-safe DSLs.
• Avoid using it in public API boundaries that must be compiled to Java—Java won’t understand reified generics.

🚀 Pro Tip: When writing coroutine-based network libraries or internal frameworks, use inline reified to make API usage cleaner and more intuitive—especially when dealing with typed responses.

Top comments (0)