Kotlin reified keyword explained

Martin Macheiner
2 min readMay 24, 2020

--

When I first started with Java, Generics became one of my favorite features. Later in my journey, I became quite fond of Reflection. Working with both often get quite cumbersome. When switching to Kotlin I found the pretty cool reified keyword that’s basically syntactic sugar and looks like magic at first glance (just like Kotlin’s extension functions). So, let’s just take a look at how we can use it in an Android example.

Initializing a ViewModel in Android was previously always a bit boilerplate to me. Frankly, I always forgot how to do it and always copied it from other classes. And the code does not look that beautiful, to be honest.

Reified extension methods to the rescue! In the snippet below, I created an extension function for Fragments that returns the exact same type of the ViewModel you want to initialize at runtime. Since type information of generic types will be erased at runtime, there’s actually no way to retrieve the type information of the desired ViewModel at runtime. The sample uses the reified keyword to specify T, which is a subtype of ViewModel. Now we can access the type of the generic T. Magic? Not exactly.

Using the reified keyword requires the method to marked as inline. Marking a method as inline just means that the code of this method will be copied to the calling side (to the calling Fragment in this case). So, not so magical at all.

However, the calling side looks now more concise and easy to understand (and easier to remember).

So essentially it’s just syntactical sugar because the actual code in the first sample just got moved into a separate method, which is then copied back to the Fragment at compile time. Still, it really increases the readability of the code.

One last note about the example code: Newer Jetpack dependencies simplified the initialization and there’s already an extension function ComponentActivty.viewModels() in the Android KTX library which does exactly the same thing.

--

--

Martin Macheiner
Martin Macheiner

No responses yet