You cannot use the universal parameter of a class as a generalized generalized (getting its T::class
token), because at run time the universal parameter is erased: Kotlin follows the practice of erasing Java types and does not have generalized generic types for classes.
(Kotlin has improved generics for built-in functions only)
Given this, you need to transfer and save the Class<T>
token so you can use it.
In addition, myFunction
in your example introduces a universal parameter, and it will be a new universal parameter that has nothing to do with the universal parameter of the class (naming both T
only adds confusion, consider them as T1
and T2
). If I understood correctly, you meant the class 'generic'.
You can probably declare an abstract val
that will store the class token, and rewrite the function so that it uses the stored class token:
abstract class AbstractClass<T : Any> constructor(protected val delegate: MyService) { protected abstract val classToken: Class<T> fun myMethod(param: Any): T? { return delegate.myMethod(param).'as'(classToken) } }
Then, a derivative of AbstractClass
will require an override of classToken
:
class TesterWork constructor(delegate: MyService) : AbstractClass<Tester>(delegate) { override val classToken = Tester::class.java }
After that, you can call the function on the TesterWork
instance without specifying a universal parameter:
val service: MyService = ... val t: Tester? = TesterWork(service).myMethod("test")
source share