0
0
Kotlinprogramming~5 mins

Reified type parameters with inline in Kotlin

Choose your learning style9 modes available
Introduction

Reified type parameters let you use the actual type inside a function. This helps when you want to check or use the type at runtime, which is usually hidden in Kotlin.

When you want to check the type of a generic parameter inside a function.
When you need to create an instance or call a function that requires the real type.
When you want to cast or filter a collection by a generic type safely.
When you want to avoid passing a Class object explicitly for type checks.
When you want to write cleaner and safer generic code that depends on type info.
Syntax
Kotlin
inline fun <reified T> functionName(params) {
    // use T inside
}

The function must be marked inline to use reified type parameters.

This allows you to use T::class or is T inside the function.

Examples
This function checks if a value is of type T using is keyword.
Kotlin
inline fun <reified T> isType(value: Any): Boolean {
    return value is T
}
This function prints the simple name of the type T.
Kotlin
inline fun <reified T> printTypeName() {
    println(T::class.simpleName)
}
This function filters a list to keep only elements of type T.
Kotlin
inline fun <reified T> filterList(list: List<Any>): List<T> {
    return list.filterIsInstance<T>()
}
Sample Program

This program defines an inline function with a reified type parameter to check if a value is of a certain type. It then tests this with an integer and a string.

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

fun main() {
    val number = 42
    val text = "hello"

    println(isOfType<Int>(number))   // true
    println(isOfType<String>(number)) // false
    println(isOfType<String>(text))   // true
}
OutputSuccess
Important Notes

You cannot use reified without inline because the type info is erased at runtime otherwise.

Reified type parameters let you avoid passing Class objects explicitly, making code cleaner.

Summary

Reified type parameters let you use the real type inside inline functions.

They help with type checks, casts, and creating instances safely.

Always mark the function inline to use reified.