【问题标题】:Cannot make a generic item in Kotlin无法在 Kotlin 中制作通用项目
【发布时间】:2020-10-19 13:50:54
【问题描述】:

我想让下面这行代码通用:

val newItem: Item = documentChange.document.toObject<Item>(Item::class.java)

工作正常。但是,当我尝试使其通用时:

val addedItem: T = documentChange.document.toObject<T>(T::class.java)

Android Studio 抱怨:

不能使用“T”作为具体类型参数。改用类。

Screenshot

我怎样才能使它通用?

【问题讨论】:

  • 在 kotlin 中,对于要访问类的泛型,您必须将其标记为具体类型,并且在内联函数中也是如此。我建议看这个YouTube video
  • @AkshayNandwana 谢谢,我会试试的。

标签: android firebase kotlin generics google-cloud-firestore


【解决方案1】:

你需要创建一个函数inline,并在泛型参数中添加reified关键字:

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

【讨论】:

  • 谢谢,让我试着回复你。
  • 如果你有时间,也许你也可以看看这个question
【解决方案2】:

这是一个以通用方式获取文档的代码

    inline fun <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)
            }
    }

【讨论】:

    猜你喜欢
    • 2020-01-29
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    相关资源
    最近更新 更多