4

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?

Sparsh Dutta
  • 2,450
  • 4
  • 27
  • 54

1 Answers1

6

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • So basically, if we use 'inline' without reified type everything will be inlined but type won't be, and if we use 'inline' along with reified type everything will be inlined along with the type. Did I understand it correctly? – Sparsh Dutta Dec 14 '21 at 16:44
  • @SparshDutta Yes you have understood correctly. – Sweeper Dec 14 '21 at 16:45
  • 1
    @SparshDutta Also, if you wonder why type params are not automatically reified for all inline functions, note that reified types have to be known at the call-site. For example, `MyClass` can invoke `inline fun `, passing `T` as `T2`, however, the same would be impossible if `T2` would be reified, because `MyClass` doesn't know its `T`. So inline functions with reified params are somewhat "harder" to invoke. – broot Dec 14 '21 at 18:00