How Reified Type makes Kotlin so much better

Reified: made (something abstract) more concrete or real. This keyword in Kotlin makes Kotlin a much better language for Android development. There’re 3 distinct nice bits as below.

No more passing clazz

This is most obvious and probably shared by many other posts you have seen describing Reified usage. For completion, I’ll put this here as well.

Imagine if you like to have a common function that starts an activity, you’ll have to have a parameter that passes in as Class<T>.

// Function
private fun <T : Activity> Activity.startActivity(
context: Context, clazz: Class<T>) {
startActivity(Intent(context, clazz))
}
// Caller
startActivity(context, NewActivity::class.java)

The reified approach

With reified, this could be simplified to just the generic type.

// Function
inline fun <reified T : Activity> Activity.startActivity(
context: Context) {
startActivity(Intent(context, T::class.java))
}
// Caller
startActivity<NewActivity>(context)

Safe unknown casting

In Kotlin, we know we have as? which will cast to the specific type and return a null if the cast…

--

--