Kotlin, in my experience, is usually a language easy to learn if you’ve already worked with OOP paradigms before. Nonetheless, once the basics are clear, it can also offer higher complexity concepts, like covariance, functional programming…
One of those concepts is the reified
keyword, which took me some time to really understand and see how I could benefit from it.
I also have an article where I talk about Kotlin delegates, in case you are interested in the topic. You can find it here.
What is reified?
This keyword changes how a function which takes a type as a parameter is called and allows the usage of the keywords is
and as
when working with generics. For example, imagine we have the following class hierarchy.

If we have a list of Smartphones
, and we want to find elements or filter them by type, Android
or iPhone
, the following function can be implemented.

Now we can filter the list of smartphones using types and return the element with the type that we specified when calling the function. It’s also possible to constraint the T type to allow only Smartphone
or even make the function an extension of List<Smartphone>
to remove all the arguments.

Without the reified
keyword, the compiler would throw an error.
Cannot check for instance of erased type: T
You may have noticed also the inline
keyword, which I’m explaining at the end of the article.
When calling our function, the difference is not huge, but it makes the code look cleaner, and a function argument is removed.

Why is inline necessary?
In Java, and other programming languages, there’s a concept known as type erasure. This means that when code is compiled, the type is lost, and the code no longer knows if you were looking for an Android
or an iPhone
. This post in StackOverflow explains it pretty well.
The inline
keyword is used to try to avoid this behaviour so that the type is not lost, and we avoid the error mentioned before.
If you are curious about bytecode and want to check this information by yourself, you can enable the Java Bytecode Decompiler plugin in Android Studio, and then go to Tools -> Kotlin -> Show Kotlin Bytecode
inline
is taking the code that the function is made of, and copying it into where the function is being called, and avoids calling the function.
For example, imagine in the following piece of code that we are seeing Java bytecode instead of Kotlin code.

This kind of concepts are sometimes hard to understand, so I recommend that right after reading this or other article about the topic, you put it into practice and experiment with it for a bit.
If you want to read more content like this without ads and support me, don’t forget to check my profile, or give Medium a chance by becoming a member to access unlimited stories from me and other writers. It’s only $5 a month and if you use this link I get a small commission.
Featured image by AbsolutVision on Unsplash