For a class with a common parameter T, you cannot do this because you do not have type information for T, since the JVM erases the type information. Therefore, such code cannot work:
class Storage<T: Any> { val snapshot: Snapshot? = ... fun retrieveSomething(): T? { return snapshot?.getValue(T::class.java)
But you can do this work if type T is validated and used inside the built-in function:
class Storage { val snapshot: Snapshot? = ... inline fun <reified T: Any> retrieveSomething(): T? { return snapshot?.getValue(T::class.java) } }
Note that the built-in function, if public can only access public members of the class. But you can have two options for a function: one that receives a class parameter that is not inline, and accesses private internal elements, as well as another built-in helper function that overrides from the inferred type parameter:
class Storage { private val snapshot: Snapshot? = ... fun <T: Any> retrieveSomething(ofClass: Class<T>): T? { return snapshot?.getValue(ofClass) } inline fun <reified T: Any> retrieveSomething(): T? { return retrieveSomething(T::class.java) } }
You can also use KClass instead of Class so that callers who are only Kotlin can simply use MyClass::class instead of MyClass::class.java
If you want the class to interact with the built-in method in generics (this means that the Storage class only stores objects of type T ):
class Storage <T: Any> { val snapshot: Snapshot? = ... inline fun <reified R: T> retrieveSomething(): R? { return snapshot?.getValue(R::class.java) } }
Reference to reified types in built-in functions: https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters
source share