如何在LiveData< I>中使用"I"作为已确定类型的参数.班级? [英] How to use 'I' as reified type parameter in a LiveData<I> class?
本文介绍了如何在LiveData< I>中使用"I"作为已确定类型的参数.班级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在尝试将LiveData<I> class
子类化时,我尝试使用泛型.根据这个答案,我已经尝试过:
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)
}
我收到此错误:
Cannot use 'I' as reified type parameter. Use a class instead.
检查此打印屏幕
有人可以帮我吗?
推荐答案
该类的I
类型无法进行验证,因此您无法为该函数创建重载的验证化I
.我认为您可以通过使类成为构造函数参数来手动调整类类型.像这样:
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)
}
这篇关于如何在LiveData< I>中使用"I"作为已确定类型的参数.班级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文