reified
- Kotlin course
- Expert
- Lesson 3/47
- 5 min
Learn runtime type safety with reified.
What is reified?
Normally inside a generic function you cannot access the runtime type of T because the JVM applies type erasure. reified bypasses that.
If you mark a type parameter of an inline function as reified, the compiler substitutes the actual type at the call site. Example: inline fun <reified T> typeName(): String = T::class.simpleName ?: "?". Then typeName<Int>() returns "Int". reified only works in inline functions.
Filtering with reified
One common use of reified is to filter items of a specific type from a list.
Example: inline fun <reified T> List<Any>.filterOfType(): List<T> = filter { it is T }. Here the it is T check only works with reified because normally T is erased. Call: list.filterOfType<Int>(). This pattern appears in the Kotlin standard library too.
Practice Write reified typeName
Write inline fun <reified T> typeName(): String. It should return T::class.simpleName ?: "?". In main, print the results of typeName<Int>() and typeName<String>() on separate lines.
Starter code
// add reified
inline fun <T> typeName(): String = TODO()
fun main() {
// print type names for Int and String
}Sample solution
inline fun <reified T> typeName(): String = T::class.simpleName ?: "?"
fun main() {
println(typeName<Int>())
println(typeName<String>())
}Expected output
Int String
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match reified parts
| Term | Meaning |
|---|---|
inline |
Required base |
reified |
Type parameter marker |
T::class |
Runtime type |
simpleName |
Class name |
2 Which keyword must reified work with?
- suspend
- inline Correct answer
- tailrec
- operator
Explanation: reified only applies in inline functions.
3 Complete the reified typeName function
inline fun <____ T> typeName(): String = T::class.simpleName ?: "?"
inline fun <reified T> typeName(): String = T::class.simpleName ?: "?"
Explanation: reified lets you access T at runtime.