Reified Types in Kotlin

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:

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:

And then use it to return the casted object:

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

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:

Conclusion

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!

 

 

 

 

 

Facebook Comments
Get free email updates!
Signup now and receive an email once we publish new content.
We respect your privacy

Juma Allan

In this blog, I write tutorials and articles related to Android and Node Js coding. I am an Open Source Enthusiast and have been programming Android for three years now. I love sharing my knowledge with others, and learning new languages everyday. I write on this blog to share what I've gained by learning from the web and friends.