Cannot make a generic item in Kotlin

浪尽此生 提交于 2020-07-10 10:26:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!