Android Kotlin Extension - Super Challenge

I'm a Java Android developer and I'm getting closer to Kotlin

I 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, if I call .store() for any RealmObject , the extension RelamObject.store() will be called BUT, but if I call .store() on the Player instance, then the extension that will be called will be Player.store() (No problem at the moment) I do not want to copy the paste of the same code, I like to write less reuse. So I need inside Player.store() call the generic RealmObject.store()

I understood. The code I wrote actually works as expected: D

What I ask (simply because I wrote it only by personal intuition):

Is this a good way ?! Or is there a better way?

thanks

+5
source share
1 answer

Your approach seems perfectly right, because it does exactly what you need. Kotlin resolves extension calls based on the static (intended or declared) type of the recipient expression, and casting (this as RealmObject) makes the type of the static expression RealmObject .

Another correct way to do this, which I'm sure is better, is to use a link to another extension:

 fun Player.store(){ this.loggedAt = Date() (RealmObject::store)(this) } 
+2
source

Source: https://habr.com/ru/post/1270540/


All Articles