I am trying to initialize an Object based on Kotlin Type parameters. The implementing class MyClass
needs to have zero args constructor as it extends ActionCallback which does not allow parameters.
I have followed the Kotlin guide on inline functions to try and achieve this. The idea is that T
is used on MyClass
, which is used to instantiate myObject
based on the Type. However I get error Cannot use 'T' as reified type parameter. Use a class instead.
Disclaimer: I do not know if inline functions is best way to approach this. I have used this route due to not being able to pass in parameters to MyClass
but am open to other approaches.
inline fun <reified T> getObject(): T? {
return when (T::class) {
type1::class -> object1 as T?
type2::class -> object2 as T?
else -> null
}
}
class MyClass<T> : ActionCallback {
var myObject = getObject<T::class>() /*<--Error: Cannot use 'T' as reified type parameter. Use a class instead*/
}