【问题标题】:Android Kotlin Extension super callingAndroid Kotlin Extension 超级调用
【发布时间】:2017-08-03 15:06:00
【问题描述】:

我是一名 Java Android 开发人员,我正在接近 Kotlin

我已经定义了以下类:

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

我定义了以下两个扩展,一个用于通用 RealmObject 类,一个用于特定 Player 类:

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

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

我想要的是,如果我在任何RealmObject 对象上调用.store(),则将调用RelamObject.store() 扩展,但如果我在Player 实例上调用.store(),将调用的扩展将是@ 987654329@。 (暂时没问题) 我不想复制粘贴相同的代码,我喜欢少写重用。 所以我需要在内部Player.store() 将调用通用RealmObject.store()

我明白了。我在那里写的代码实际上按预期工作:D

我要问的是(只是因为我只是凭个人直觉写的):

这是好方法吗?!还是有更好的方法?

谢谢

【问题讨论】:

  • 如果代码运行正常,并且您想要的是代码审查或更好的方法来完成此任务,您应该去Code Review 并在那里发布这个疑问。

标签: kotlin super kotlin-android-extensions kotlin-extension


【解决方案1】:

您的方法似乎完全正确,因为它完全符合需要。 Kotlin 根据接收者表达式的static(推断或声明)类型解析扩展调用,并且转换(this as RealmObject) 使静态表达式类型为RealmObject

另一种我不确定是否更好的有效方法是使用对另一个扩展的可调用引用:

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

【讨论】:

    猜你喜欢
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多