Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why to use 'inline' when using a 'reified' type

All the tutorials I read about type reification say that we need to use ‘inline’ when using ‘reified’, but none of them explain why.

Let’s say I have a function:

inline fun <reified T> doSomething(value: T) {
    println("Doing something with type: ${T::class.simpleName}")    
}

As far as I understand, using ‘reified’ prevents type erasure. So why can’t we make use of it in a normal non-inlined function. Using inlined is going to make the compiler copy the body of the above function at the call sites. But why do we need that to happen?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Reified types are not magic – type erasure still happens as usual. So how does reified types work? Well, let’s say I call:

doSomething("Foo")

The compiler works out that T is String. And it can directly translate the above line into:

println("Doing something with type: ${String::class.simpleName}")

Therefore, at a surface level, it looks like as if the type is reified, but in actuality, the type is just inlined. This is also why the function needs to be inline. If it is not inline, the compiler cannot inline the type parameter.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading