No more type erasure!

Kotlin reified Explained (no more type erasure)

Michal Ankiersztajn
ProAndroidDev
Published in
2 min readJul 1, 2024

--

In Kotlin, when working on a JVM environment such as Android, Desktop or Spring Boot, the types are erased at runtime, which limits your ability to write generic and readable algorithms.

However, Kotlin solved this problem by introducing reified the keyword, which preserves the type in runtime.

How does it work?

There are some limitations to using reified. Your function must be inlined. What does inlining do? It moves all the code from a function to a place of a call. It’s best to look at an example so you can visualize it yourself:

inline fun printWords(word1: String, word2: String) {
println(word1)
println(word2)
}

fun main() {
printWords("Hello", "World")
printWords("Example", "Word")
}

// Is then compiled at runtime into:
fun main() {
println("Hello")
println("World")
println("Example")
println("Word")
}

That means, at runtime, the function code will be moved across its uses.

reified

You might start to see what’s going on.

Since you’re moving all the code to compilation at the place of a call => it means you can use it as if it were at that place.

This is a compelling statement; it’s a key to understanding how reified works. Since you can write code as if it were at the place of a call, there’s no type erasure because the type is known at that place. Take a look at the example:

fun main() {
val word = "Word"
// At the place where the val is defined the type is known
println(word::class.simpleName) // String
}

// THIS CODE DOESN'T WORK
fun <T> printType() {
println(T::class.simpleName)
}

// This code works because of inline + reified
inline fun <reified T> printType(any: T) {
println(T::class.simpleName)
}

// Usage
fun main() {
val word = "Word"
printType(word) // String
}

As you can see, in reality reified is truly a clever use of inline function behaviour. Now go and write better and more generic algorithms yourself!

Thanks for reading. Please clap and follow me if you’ve learned something new! :)

More on inlined functions:

--

--