How to use 'I' as reified type parameter in a LiveData<I> class?

旧城冷巷雨未停 提交于 2020-07-10 10:26:38

问题


I'm trying to use generics when subclassing a LiveData<I> class. According to this answer, I have tried this:

class ItemLiveData<I>(): LiveData<I>() {

    override fun onEvent(querySnapshot: QuerySnapshot?, e: FirebaseFirestoreException?) {
        if (e != null) return

        for (documentChange in querySnapshot!!.documentChanges) {
            when (documentChange.type) {
                DocumentChange.Type.ADDED -> setValue(getItem(documentChange)) //Add to LiveData
            }
        }
    
    private inline fun <reified I> getItem(doc: DocumentChange) = doc.document.toObject<I>(I::class.java)
}

I get this error:

Cannot use 'I' as reified type parameter. Use a class instead.

Check this printscreen.

Can anyone help me with that?


回答1:


The class's I type cannot be reified, and so you can't create an overloaded reified I for that function. I think you can manually reify the class type by making the class a constructor parameter. Like this:

class ItemLiveData<I>(private val type: Class<I>): LiveData<I>() {

    override fun onEvent(querySnapshot: QuerySnapshot?, e: FirebaseFirestoreException?) {
        if (e != null) return

        for (documentChange in querySnapshot!!.documentChanges) {
            when (documentChange.type) {
                DocumentChange.Type.ADDED -> setValue(getItem(documentChange)) //Add to LiveData
            }
        }
    
    private fun getItem(doc: DocumentChange) = doc.document.toObject<I>(type)
}


来源:https://stackoverflow.com/questions/62642880/how-to-use-i-as-reified-type-parameter-in-a-livedatai-class

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