Reified type parameters for inline classes

As far as I know, this should be possible.

inline class Blah<reified T>(val name: String) {
     fun bloh(): String {
          return "${T::class.simpleName}: $name"
     }
}

I’m not sure how much needs to be explained, it’d work similar to reified type parameters in inline functions.

This is currently not possible but it’d make sense to implement it as a feature.

1 Like

This is not possible to to the type errasure of the JVM. Currently inline classes can’t be inlined in all cases (generics is the one example I can think of right now). This means that there is no way for an inline class to have access to a reified type, since that relies on inlining.

1 Like

Take a look here Typeclass KClass

While this is not supported by Kotlin in this form, you can still simulate it without sacrificing the convenient API of your class this way:

fun main() {
    println(Blah<Int>("foo").bloh()) 
    // prints Int: foo
}
    
    
class Blah<T : Any>(val name: String, val clazz: kotlin.reflect.KClass<T>) {
     fun bloh(): String {
          return "${clazz.simpleName}: $name"
     }

     companion object {
          inline operator fun <reified T : Any> invoke(name: String) = Blah(
              name, T::class
          )
     }
}
3 Likes

Wow, that’s a really interesting approach! I’ll definitely take advantage of that.