How do you fix filterWrapper so it filters by T without reflection?
This function tries to keep only elements of type T, but it does not compile because T is erased at runtime. Fix it so it works without passing a Class argument and without reflection.
fun <T> filterWrapper(data: List<Any>): List<T> =
data.filterIsInstance(T::class.java) // won't compile: T is erased
Find and fix the bug.
A plain T is erased, so T::class.java is unavailable. Make it inline with a reified parameter: inline fun <reified T> filterWrapper(data: List<Any>) = data.filterIsInstance<T>(). Inlining substitutes T's real type at the call site — no reflection.
- ✗Trying
T::class.javain a non-inline function whereTis erased - ✗Thinking only passing a
Class<T>argument can solve it, missingreified - ✗Marking the parameter
reifiedwithout also making the functioninline
- →Why must a
reifiedtype parameter always live on aninlinefunction? - →What runtime check does
filterIsInstance<T>()perform on each element?
The bug
The type parameter T is erased on the JVM, so inside an ordinary function there is no T::class.java token. The code does not compile.
fun <T> filterWrapper(data: List<Any>): List<T> =
data.filterIsInstance(T::class.java) // ❌ T is erased
The fix
Make the function inline and the parameter reified. When inlined, the compiler substitutes the concrete T directly at the call site, so the type is available at runtime with no reflection.
inline fun <reified T> filterWrapper(data: List<Any>): List<T> =
data.filterIsInstance<T>() // ✅ T is known
reified works only with inline: without inlining there is nowhere to substitute the real type. filterIsInstance<T>() checks each element with is T.