gpt4 book ai didi

kotlin - 如何在匿名类中引用自己?

转载 作者:IT老高 更新时间:2023-10-28 13:42:06 46 4
gpt4 key购买 nike

我在 kotlin 中有下一个代码:

handler.postDelayed(object : Runnable {
override fun run() {
Timber.i("run post msg")
handler.postDelayed(this, AppPrefs.SEARCH_DELAY)
}
},AppPrefs.SOCKET_INTERVAL)

您如何看待创建延迟任务的简单标准方法(使用 Runnable class)。值 this 引用 anonimus 对象实现 Runnable 并编译并正常工作

但是当我为此制作 lamdba 时:

handler.postDelayed({
Timber.i("run post msg")
handler.postDelayed(this, AppPrefs.SOCKET_INTERVAL)
},AppPrefs.SOCKET_INTERVAL)

value this 引用了外部类。

如何从内部匿名类引用到你自己?

最佳答案

你不能这样做。一个 similar question在 Kotlin 的论坛上被问到,yole(该语言的创造者之一)这样说:

this in a lambda refers to the instance of the containing class, if any. A lambda is conceptually a function, not a class, so there is no such thing as a lambda instance to which this could refer.

The fact that a lambda can be converted into an instance of a SAM interface does not change this. Having this in a lambda mean different things depending on whether the lambda gets SAM-converted would be extremely confusing.

关于kotlin - 如何在匿名类中引用自己?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44696398/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com