In this blog, we are going to learn about Reified types. Wait, what is this weird term called Reified? Don't worry, that's the topic for today's blog. Let’s write another example.Since you are reading this blog, you must agree to the point thatĪnd this is because of its unique features as compared to other programming languages. The inline reification works like a charm: > val set = setOf("1984", 2, 3, "Brave new world", 11) If we declare the previous function as inline and mark the type parameter as reified, then we can access generic type information at runtime: inline fun Iterable.filterIsInstance() = filter That is, the compiler substitutes the body directly into places where the function is called instead of the normal function invocation.
Type parameters of inline functions can be reified, so we can refer to those type parameters at runtime. The type erasure rule is true in general, but there is one case where we can avoid this limitation: Inline functions. So, every time we get an element from it, the compiler would cast it to a String or when we’re gonna add an element into it, the compiler would type check the input. The compiler is the one responsible for erasing the type information but before that, it actually knows the books variable contains String elements. So, how does Kotlin’s compiler prevent us from adding a Non-String into a Set? Or, when we get an element from a Set, how does it know the element is a String?
Let’s create two Sets with two different type parameters: val books: Set = setOf("1984", "Brave new world")Īt runtime, the type information for Set and Set will be erased and we see both of them as plain Sets. So, even though it’s perfectly possible to find out at runtime that value is a Set, we can’t tell whether it’s a Set of strings, integers, or something else: that information has been erased. For example, if we create a Set and put a few strings into it, at runtime we’re only able to see it as a Set.