【问题标题】:Best alternative for object keyword in kotlinkotlin 中对象关键字的最佳替代方案
【发布时间】:2019-10-12 23:41:15
【问题描述】:
 private val timer = object : CountDownTimer(result, 1000) {
    override fun onFinish() {
        //delete the database entry
    }

    override fun onTick(millisUntilFinished: Long) {
        //more code

    }

}

据我对 kotlin 的了解,对象在 result 被赋值之前被调用

最初,result 的值为 0,然后它在另一个函数中更新,但定时器被调用,result 的值为 0。

那么这里的object 的最佳替代品应该是什么?

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    你可以保留object,你只需要改变初始化的顺序。一种方法是使用by lazy,如下所示:

        var result = 0L
    
        private val timer: CountDownTimer by lazy {
            object : CountDownTimer(result, 1000) {
                override fun onFinish() {
                    // delete the database entry
                }
    
                override fun onTick(millisUntilFinished: Long) {
                    // more code
                }
            }
        }
    
        // 'init' block just as an example; the below code works anywhere
        // such as in onCreate(), onStart() or wherever
        init {
            result = 1000
            // 'timer' is initialized with result=1000 and then started
            timer.start()
        }
    

    lazy 是一个所谓的属性委托,您可以在official docs 中了解更多信息。

    【讨论】:

    • 现在我得到编译错误,错误:找不到符号 symbol: class $timer$2$1 Works with android?
    • 尝试清理并重建您的项目。如果这没有帮助,我建议您在此站点上提出一个新问题,其中包含您的构建系统的详细信息、其配置以及您遇到问题的确切代码。
    • 这个特定的代码给出了错误 - 我什至还没有调用它
    • 这是错误 -- stackoverflow.com/questions/53168385/… 一种解决方法是明确指定类型。一种解决方法是明确指定 foo 的类型。现在我们如何在我的情况下做到这一点?
    • 很高兴您找到了错误的原因!我已更新我的答案以明确指定timer 的类型(在您的情况下不是foo),如您链接到的问题中指定的那样。请问我现在可以收回我的投票吗? :)
    【解决方案2】:

    我不明白这与 Kotlin 有什么关系?

    • 你有一个成员 val: timer
    • 在创建 val 所在的对象时对其进行初始化。

    所以问题不在于您使用的是什么语法。这是您创建计时器的时间。如果您知道何时使用它,并且确定此时结果将被初始化,则可以使用延迟初始化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 2010-11-27
      • 2018-01-27
      相关资源
      最近更新 更多