One of the limitations that most frustrates Java developers when using generics is not being able to use the type directly.

Normally this is solved by passing the class as a function parameter, making the code more complex and unattractive.

In Kotlin, thanks to the inline functions, which we’ve already discussed, we can use reified types that will allow us to use them within the functions.

What is this for? You’ll see, you’re gonna like it.

Reified types

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).

And if you want to start using Kotlin to develop your own apps, I recommend you to take a look a the free guide and Kotlin for Android Developers book.

Author: Antonio Leiva

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares
%d bloggers like this: