Site Loader
Join Academy

Another lesson for today! And this one is really special, another show of how you can do things in Kotlin that are impossible in Java. Reified types are a way to make typed functions able to use its type inside their body. That’s not possible in Java, and the only thing you can do is to set the class as an argument of the function.

Reified Types in Kotlin

As I commented earlier, by marking a type as reified, we’ll have the ability to use that type within the function.

It is important that the function that uses it is inline, since the code needs to be replaced in the place from which it is run in order to have access to the type. The fact that types can not be used in functions is a limitation of the Java Virtual Machine, and that’s the “trick” to skip that limitation.

Navigating to an Activity

This is the most typical case applied to Android.

In Java, when we call startActivity, we need to specify the destination class as a parameter.

In Kotlin, we can simplify it by adding the type to the function:

inline fun <reified T : Activity> Activity.startActivity() {

Navigating to an Activity is now as easy as this:


FindView with casting

Something that not many Android developers use in Java and that is quite helpful is using generics to return the objects casted to the type of the variable that the result is assigned to.

In Java, you can create a function like this:

public <T extends View> T findView(Activity activity, int id) {
    return (T) activity.findViewById(id);

And then use it to return the casted object:

TextView textView = Utils.findView(activity,;

Something similar can be done with Kotlin, but easier thanks to extension functions:

fun <T : View> Activity.findView(id: Int) = findViewById(id) as T

val textView = activity.findView<TextView>(

But in both cases you’ll find that the compiler can’t be sure that the cast is valid, because it doesn’t have access to the type of T, so it will show a warning.

With reified types, you can avoid this issue:

inline fun <reified T : View> Activity.findView(id: Int) = findViewById(id) as T


With reified types you can do things that are impossible in Java, and even do some other functions safer.

Now, you can avoid passing an argument of type Class to your functions.

Besides, thanks to extension functions, you can create new functions over frameworks such as Android, which already use this in some parts of its API (as the startActivity method does).

If you want to see all this and much more while writing a real App, I recommend you to subscribe to this blog.

I’d love to see if / where you’re using Kotlin, so please drop me a comment or leave a response if you have anything to share (or even any questions to ask!)

Happy Coding!






Post Author: academy

School of {Code}

Leave a Reply

Your email address will not be published. Required fields are marked *

Academy Archives