In Kotlin, reified
types are used with inline
functions to enable type information to be available at runtime. Normally, type parameters in generics are erased at runtime due to type erasure, but reified
allows the type to remain available for reflective operations or type-specific logic.
Here are the key points to use reified
types with inline
functions:
- Mark the function as
inline
: The function must be aninline
function for it to usereified
types. - Use the
reified
modifier: The generic type parameter must be marked asreified
to prevent type erasure and keep the type information available at runtime. - Call the function without explicitly passing the type: The compiler will infer the type automatically.
Here’s an example that demonstrates using reified
types:
Example: Filtering a List Based on Type
inline fun <reified T> List<Any>.filterByType(): List<T> {
return this.filter { it is T }.map { it as T }
}
fun main() {
val mixedList: List<Any> = listOf(1, "Hello", 2.5, "World", 42)
// Use the reified function to filter only Strings
val strings: List<String> = mixedList.filterByType()
println(strings) // Output: [Hello, World]
// Use the reified function to filter only Integers
val integers: List<Int> = mixedList.filterByType()
println(integers) // Output: [1, 42]
}
Explanation:
- Inline Functions: Inline functions replace the function body at the call site, enabling the type information to persist after type erasure.
- Reified Modifier: When you use
reified T
, you can check the type (it is T
) or even fetch its class (T::class
) at runtime because the type information is preserved. - Flexible Filtering: In the above example, the
filter
function dynamically determines the type of each element and includes the matching elements in the resulting list.
When to Use Reified Types
- When you need access to the type at runtime (e.g., to perform type checking or reflection).
- When working with generic functions that act differently based on the type parameter.
Note:
- You can only use
reified
with inline functions. - Avoid overusing
inline
functions, as they can increase code size due to function duplication at each call site.