我有一个现有的 Java 类ThreadUtils
,其方法every
如下:
public class ThreadUtil {
public static Thread every(int seconds, Runnable r) {
Thread t = new Thread(() -> {
while(true) {
r.run();
try {
Thread.sleep(1000 * seconds);
} catch (InterruptedException e) {
return;
}
}
});
t.start();
return t;
}
}
我正在尝试将其转换为 Kotlin。我对 Runnable 关闭有点犹豫。这失败了一个坏的return
:
fun every(seconds: Int, r: Runnable): Thread {
val t = Thread({
while (true) {
r.run()
try {
Thread.sleep((1000 * seconds).toLong())
} catch (e: InterruptedException) {
return // ERROR: This function must return a value of type Thread
}
}
})
t.start()
return t
}
我还尝试将 Runnable 拉出来只是为了帮助自己分离事物,但这也以同样的方式失败:
fun every(seconds: Int, r: Runnable): Thread {
val internalRunnable = Runnable {
while (true) {
r.run()
try {
Thread.sleep((1000 * seconds).toLong())
} catch (e: InterruptedException) {
return // ERROR: This function must return a value of type Thread
}
}
}
val t = Thread(internalRunnable)
t.start()
return t
}
如何实现一个@FunctionalInterface
或类似样式的闭包/ lambda,它不尝试return
从定义它的函数中获取?