How to call inline reified function with unknown class?


For example:

inline fun <reified T>foo() {

fun main(args: Array<String>) {
    class Bar
    foo<Bar>() // ok
    // what about this?
    val unknownClass = Bar::class


Short answer, you can’t :stuck_out_tongue_winking_eye:

The way reified inline functions work in Kotlin is that as the name says they get inlined into the place where you call them. Therefor every time you use the type parameter in your inline function it gets replaced by the actual type. So when you call foo<Bar>() it replaces the call (in your case) with println(Foo::class).
Because of this you can use type checking ( someVariable is T), etc which you normally would not be able to use with just a reference to the class.

This does not mean you can never do something like this. As long as you can write your “reified” function in a way in which you don’t use the type parameter directly but use the class instead you can do something like this

fun <T>foo(clazz: KClass<T>){
inline fun <reified T>foo() = foo(T::class)

Also as far as I know it should be possible to simulate a type parameter using a reference to a KClass in terms of functionality. The resulting code will most likely be harder to read though and I don’t know how much of a performance impact this might have. I guess for some features you need reflection which can get quite complicated.