Home > front end >  Why to use 'inline' when using a 'reified' type
Why to use 'inline' when using a 'reified' type

Time:12-15

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?

CodePudding user response:

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.

  • Related