Kotlin Academy · Lesson

Practical Reified Patterns: Parsing, DI & Serialization

Apply reified generics to JSON parsing, dependency resolution, and reflection helpers.

Lesson 4 of 414 steps

Practical Reified Patterns: Parsing, DI & Serialization is a free Kotlin Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.

The Three Main Use Cases

Reified type parameters shine in three recurring Kotlin patterns: JSON/data parsing, dependency injection, and serialization helpers. Each eliminates boilerplate ::class.java arguments.

Pattern 1 — Type-Safe JSON Parsing

Wrap Gson or Jackson in a reified extension so callers never pass a Class explicitly:

inline fun <reified T> String.parseJson(): T =
    Gson().fromJson(this, T::class.java)

val user: User = jsonString.parseJson()

Parsing Collections

Parsing a generic list requires a TypeToken. With reified you can hide this complexity:

inline fun <reified T> String.parseList(): List<T> {
    val type = object : TypeToken<List<T>>() {}.type
    return Gson().fromJson(this, type)
}

val users: List<User> = jsonString.parseList()

kotlinx.serialization Approach

kotlinx.serialization already uses reified internally. The top-level decodeFromString() relies on serializer() which is a reified inline function.

val user = Json.decodeFromString<User>(jsonString)
// equivalent to: Json.decodeFromString(serializer<User>(), jsonString)

Pattern 2 — Service Locator / DI

A simple service locator can resolve dependencies by type without callers passing a KClass:

object ServiceLocator {
    val registry = mutableMapOf<KClass<*>, Any>()
    inline fun <reified T : Any> get(): T =
        registry[T::class] as? T ?: error("No binding for ${T::class}")
    inline fun <reified T : Any> bind(instance: T) {
        registry[T::class] = instance
    }
}

ViewModel Retrieval in Android

The most common Android reified pattern:

inline fun <reified VM : ViewModel> ComponentActivity.viewModel(): VM =
    ViewModelProvider(this)[VM::class.java]

// Usage
val vm: MyViewModel by lazy { viewModel() }

Pattern 3 — Safe Casting Helper

A reified cast helper with a fallback is cleaner than explicit as? everywhere:

inline fun <reified T> Any?.safeCast(): T? = this as? T

val name: String? = someAny.safeCast<String>()

Type-Checking Collections

The standard filterIsInstance() is the canonical reified collection filter. You can build higher-level variants on top of it:

inline fun <reified T> List<Any>.onlyInstancesOf(block: (T) -> Unit) =
    filterIsInstance<T>().forEach(block)

items.onlyInstancesOf<Button> { it.setEnabled(true) }

Registering Event Listeners by Type

An event bus that dispatches by type becomes ergonomic with reified:

class EventBus {
    val handlers = mutableMapOf<KClass<*>, (Any) -> Unit>()
    inline fun <reified E : Any> on(noinline handler: (E) -> Unit) {
        handlers[E::class] = { handler(it as E) }
    }
    fun post(event: Any) = handlers[event::class]?.invoke(event)
}

Combining reified with Extension Functions

Reified extension functions on generic receivers give APIs a fluent feel while keeping type-safety:

inline fun <reified T : Any> SharedPreferences.get(key: String, default: T): T = when (T::class) {
    Int::class    -> getInt(key, default as Int) as T
    String::class -> getString(key, default as String) as T
    Boolean::class -> getBoolean(key, default as Boolean) as T
    else -> error("Unsupported type ${T::class}")
}

Limits to Keep in Mind

Remember: reified works only in inline functions. Classes and interfaces cannot have reified type parameters. If you need runtime type information in a class, store a KClass property instead.

Testing Reified Helpers

Reified functions are straightforward to test — call them with concrete type arguments in unit tests and assert the output type and value. No mocking of class references is needed.

val result: List<String> = """["a","b","c"]""".parseList<String>()
assertEquals(listOf("a","b","c"), result)

Quick Check

Which statement about reified functions is correct?

Recap: Practical Reified Patterns

Key patterns:

  • JSON parsing: hide Class/TypeToken arguments
  • DI/Service Locator: resolve by type without KClass parameters
  • Safe casting and collection filtering
  • Event bus dispatch by event type
  • SharedPreferences / typed key-value stores
Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Practical Reified Patterns: Parsing, DI & Serialization” lesson free?

Yes — any 3 lessons of the Kotlin Academy learning path, including “Practical Reified Patterns: Parsing, DI & Serialization”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.

What will I learn in “Practical Reified Patterns: Parsing, DI & Serialization”?

Apply reified generics to JSON parsing, dependency resolution, and reflection helpers. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

How long does the “Practical Reified Patterns: Parsing, DI & Serialization” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. inline Functions: Eliminating Lambda Overhead
  2. noinline and crossinline Modifiers
  3. reified Type Parameters: Accessing T at Runtime
  4. Practical Reified Patterns: Parsing, DI & Serialization
← Back to Kotlin Academy