Skip to content Skip to sidebar Skip to footer

Cannot Make A Generic Item In Kotlin

I want to make the following line of code generic: val newItem: Item = documentChange.document.toObject(Item::class.java) Works fine. However, when I try to make it ge

Solution 1:

You need to make a function inline and add reified keyword to the generic parameter:

inlinefun<reified T>someFun() {
    //...val addedItem: T = documentChange.document.toObject<T>(T::class.java)
}

Solution 2:

Here is a code for getting the document in a generic way

inlinefun<reified T>getDocumentItemByName(directory: String, crossinline returnResult: (result : T) -> Unit) {

        firestore.collection(directory).get()
            .addOnSuccessListener {
                OnSuccessListener<QueryDocumentSnapshot> { documentSnapshot ->

                    var entity = documentSnapshot.toObject<T>(T::class.java)
                    returnResult(entity)

                }
            }
            .addOnFailureListener { exception ->
                Log.w(TAG, "Error getting documents: ", exception)
            }
    }

Post a Comment for "Cannot Make A Generic Item In Kotlin"