问题
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