Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Kotlin Extension super calling

i am a Java Android Developer and i'm approaching to Kotlin

I have defined the following class:

open class Player : RealmObject() {
    ...
}

And i defined the following two extensions, one for the generic RealmObject class and one for the specific Player class:

fun RealmObject.store() {
    Realm.getDefaultInstance().use { realm ->
        realm.beginTransaction()
        realm.copyToRealmOrUpdate(this)
        realm.commitTransaction()
    }
}

fun Player.store(){
    this.loggedAt = Date()
    (this as RealmObject).store()
}

What i want is if i call .store() on any RealmObject object, the RelamObject.store() extension will be called BUT if i call .store() on a Player instance the extension that will be called will be Player.store(). (No problem for now) I don't want to copy paste the same code, i love to write less reuse more. So i need that internally the Player.store() will call the generic RealmObject.store()

I got it. The code i wrote up there is actually working as expected :D

What i am asking is (just because i wrote that just by personally intuition):

Is this the good way?! Or there is some better way?

Thank you

like image 747
Gianni Genovesi Avatar asked Oct 30 '22 04:10

Gianni Genovesi


1 Answers

Your approach seems to be perfectly correct, because it does exactly what is needed. Kotlin resolves the extension calls based on the static (inferred or declared) type of the receiver expression, and the cast (this as RealmObject) makes the static expression type RealmObject.

Another valid way to do this, which I'm not sure is better, is to use a callable reference to the other extension:

fun Player.store(){
    this.loggedAt = Date()
    (RealmObject::store)(this)
}
like image 137
hotkey Avatar answered Nov 07 '22 22:11

hotkey