Reified
- Kotlin course
- Intermediate
- Lesson 51/116
- 5 min
Learn runtime type info with reified.
Reified
reified makes a generic type parameter accessible at runtime. Normally generic type parameters are erased (type erasure); reified bypasses this.
Example: inline fun <reified T> typeName(): String { return T::class.simpleName ?: "Unknown" }. This function is called as typeName<Int>() and returns "Int". reified only works with inline functions, because the type information is inlined into the call site. This enables runtime checks with generic types.
The typeName function
A reified generic function accesses the type parameter's class information. T::class gives the class reference.
Example: inline fun <reified T> typeName(): String { return T::class.simpleName ?: "Unknown" }. Calling typeName<Int>() returns "Int". T::class is Kotlin reflection; .simpleName returns the short class name. ?: "Unknown" provides null safety. reified is useful for generic type checks and filtering.
Practice The typeName reified function
Define the function inline fun <reified T> typeName(): String whose body returns T::class.simpleName ?: "Unknown". In main call println(typeName<Int>()).
Starter code
// Define the typeName reified generic function
// return the class name
// call with Int in main and printSample solution
inline fun <reified T> typeName(): String {
return T::class.simpleName ?: "Unknown"
}
fun main() {
println(typeName<Int>())
}Expected output
Int
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the reified parts
| Term | Meaning |
|---|---|
inline fun <reified T> |
inline and reified signature |
T::class |
Class reference |
.simpleName |
Simple name |
typeName<Int>() |
Call |
2 Why is <code>reified</code> used with an <code>inline</code> function?
reified cannot work without inline; the type information must be inlined.- Because inline is faster
- To avoid a syntax error without inline
- To inline the type information at the call site Correct answer
- Because reified can only be called with inline
Explanation: inline inlines the type information at the call site, making reified possible.
3 Complete the reified definition
inline fun <____ T> typeName(): String {
return T::class.simpleName ?: "Unknown"
}
inline fun <reified T> typeName(): String {
return T::class.simpleName ?: "Unknown"
}
Explanation: reified T makes the type parameter accessible.