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.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |