【问题标题】:Kotlin extension function with Generic doesn't work with Any?带有 Generic 的 Kotlin 扩展功能不适用于 Any?
【发布时间】:2018-06-21 09:52:13
【问题描述】:

我想要一个 RealmList 类的扩展函数:

private inline fun RealmList<Any?>.saveAll() {
    this.forEach {
        item -> Realm.getDefaultInstance().insert(item!! as RealmModel)
    }
}

但是每当我使用它时,就会出现这个错误:

【问题讨论】:

  • 这是因为“协方差”。 RealmList&lt;Accommodation?&gt; 不是 RealmList&lt;Any?&gt;(例如,您可以在后者中放置 Int
  • 试试RealmList&lt;out Any?&gt;
  • 天哪。不要那样打电话给Realm.getDefaultInstance()。您必须将每个 getInstance() 调用与 close() 调用配对,它在文档中

标签: android generics kotlin realm extension-function


【解决方案1】:

要实现这一点,请将 out 添加到扩展函数的通用声明中。 如果在RealmList

中声明了这样的声明,它将起作用
private inline fun RealmList<out Any?>.saveAll() {
    this.forEach {
        item -> Realm.getDefaultInstance().insert(item!! as RealmModel)
    }
}

【讨论】:

  • 天哪。不要这样打电话给Realm.getDefaultInstance()。您必须将每个 getInstance() 调用与 close() 调用配对,它在文档中
【解决方案2】:

您的代码通常是不安全的。请修复您的代码,阅读文档,诸如此类。

此外,RealmList 需要? extends RealmModel,因此您需要将T: RealmModelout 一起使用。

fun <T: RealmModel> RealmList<out T?>.saveAll() {
    Realm.getDefaultInstance().use { realm ->
        val wasInTransaction = realm.isInTransaction()
        try {
            if(!wasInTransaction) {
                realm.beginTransaction()
            }
            this.forEach {
                item -> item?.let { realm.insert(it) }
            }
            if(!wasInTransaction) {
                realm.commitTransaction()
            }
        } catch(e: Throwable) {
            if(realm.isInTransaction()) {
                realm.cancelTransaction()
            }
        }
    }
}

【讨论】:

  • 投反对票,呵呵。好吧,我会在你收到mmap failed(): out of memory size: 1048576 offset: 3145728时见到你
【解决方案3】:

也许您应该使用 Realms 方法插入而不是执行循环?这样你的扩展就变成了一个简单的调用:

fun <T: RealmModel> RealmList<out T?>.saveAll() = Realm.getDefaultInstance().insert(this)

【讨论】:

  • 天哪。不要那样打电话给Realm.getDefaultInstance()。您必须将每个 getInstance() 调用与 close() 调用配对,它在文档中
  • 我只是把它写在了我的脑海中,我仍然认为这很奇怪,因为 insert 应该包装在事务中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-13
  • 2023-03-06
  • 2015-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
相关资源
最近更新 更多