将无限期运行的 Runnable 从 java 转换为 kotlin
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44789492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert indefinitely running Runnable from java to kotlin
提问by Binoy Babu
I have some code like this in java that monitors a certain file:
我在java中有一些这样的代码来监控某个文件:
private Handler mHandler = new Handler();
private final Runnable monitor = new Runnable() {
public void run() {
// Do my stuff
mHandler.postDelayed(monitor, 1000); // 1 second
}
};
This is my kotlin code:
这是我的 kotlin 代码:
private val mHandler = Handler()
val monitor: Runnable = Runnable {
// do my stuff
mHandler.postDelayed(whatToDoHere, 1000) // 1 second
}
I dont understand what Runnable
I should pass into mHandler.postDelayed
. What is the right solution? Another interesting thing is that the kotlin to java convertor freezes when I feed this code.
我不明白Runnable
我应该传递什么mHandler.postDelayed
。什么是正确的解决方案?另一个有趣的事情是,当我提供此代码时,kotlin 到 java 转换器会冻结。
回答by Miha_x64
Lambda-expressions do not have this
, but object expressions (anonymous classes) do.
Lambda 表达式没有this
,但对象表达式(匿名类)有。
object : Runnable {
override fun run() {
handler.postDelayed(this, 1000)
}
}
回答by Hobo Joe
A slightly different approach which may be more readable
一种稍微不同的方法,可能更具可读性
val timer = Timer()
val monitor = object : TimerTask() {
override fun run() {
// whatever you need to do every second
}
}
timer.schedule(monitor, 1000, 1000)