I have an existing Java class ThreadUtils
with a method every
that looks like:
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;
}
}
And I'm trying to convert it to Kotlin. I'm a bit hung up on the Runnable closure. This fails with a bad 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
}
I also tried pulling the Runnable out just to help myself separate things, but this also fails the same way:
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
}
How can I implement a @FunctionalInterface
or similar-style closure/lambda that doesn't try to return
from the function in which it's being defined?