Reified generics

In the previous section, we described how you cannot know what generic type arguments are used during runtime because of type erasure. The following code tries to get the class type of the generic argument, but will not compile because the runtime doesn’t have information about the generic T type that will be used when invoking this function:

fun <T> createInstance(): T {

//compiler error
return T::class.java.newInstance()

}

Knowing generic type information can sometimes be useful and Kotlin can bypass this limitation with reified generics. A generic type can be reified with inline functions. We explained how inlining works in the previous chapter.

When the compiler sees an inline function, it places the inlined function directly into the call site.

This is needed for reification to work since Kotlin has to produce Java compatible bytecode, so it has to erase the generic type information during compilation. The same as lambda inlining, the compiler knows which code is calling an inline marked function, and in the case of generics, it knows which generic type argument is being used. The generic function will still go under type erasure but the bytecode will already have generic type information.

Now that we know the internals of reified generics, let’s compile the previous example:

inline fun <reified T> createReifiedInstance():T {

return T::class.java.newInstance()

}

Besides the required inline keyword, you have to add the reified keyword before the generic parameter. And then, inside the function, we can access the generic type as if there was no type erasure.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.226.109