问题
I want to make the following line of code generic:
val newItem: Item = documentChange.document.toObject<Item>(Item::class.java)
Works fine. However, when I try to make it generic:
val addedItem: T = documentChange.document.toObject<T>(T::class.java)
Android Studio is complaining:
Cannot use 'T' as reified type parameter. Use a class instead.
Screenshot
How can I make it generic?
回答1:
You need to make a function inline and add reified keyword to the generic parameter:
inline fun <reified T> someFun() {
//...
val addedItem: T = documentChange.document.toObject<T>(T::class.java)
}
来源:https://stackoverflow.com/questions/62637460/cannot-make-a-generic-item-in-kotlin