1

I want to have an extension function from the RealmList class:

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

But whenever I use it, this error appears:

enter image description here

Dale Julian
  • 1,560
  • 18
  • 35

3 Answers3

3

To achieve that add out to generic declaration of your extension function. It would work if such declaration was stated in the RealmList

private inline fun RealmList<out Any?>.saveAll() {
    this.forEach {
        item -> Realm.getDefaultInstance().insert(item!! as RealmModel)
    }
}
Demigod
  • 5,073
  • 3
  • 31
  • 49
  • Omg. Don't call `Realm.getDefaultInstance()` like that. You have to pair every getInstance() call with a close() call, it's in the docs – EpicPandaForce Jun 21 '18 at 10:54
2

Your code is generally unsafe. Please fix your code, read the documentation, stuff like that.

Also, RealmList expects ? extends RealmModel, so you need to use T: RealmModel with out.

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()
            }
        }
    }
}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
-1

Maybe you should use Realms method to insert instead of performing your loop? That way your extension becomes a simple call:

fun <T: RealmModel> RealmList<out T?>.saveAll() = Realm.getDefaultInstance().insert(this)
Pawel
  • 15,548
  • 3
  • 36
  • 36
  • Omg. Don't call `Realm.getDefaultInstance()` like that. You have to pair every getInstance() call with a close() call, it's in the docs – EpicPandaForce Jun 21 '18 at 10:53
  • I just wrote that off top of my head, I still think this is weird since insert should be wrapped within a transaction. – Pawel Jun 21 '18 at 11:59