[英]Converting Thread/Runnable implementation from Java to Kotlin
I have an existing Java class ThreadUtils
with a method every
that looks like: 我有一个现有的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;
}
}
And I'm trying to convert it to Kotlin. 而我正在尝试将其转换为Kotlin。 I'm a bit hung up on the Runnable closure. 我在Runnable关闭时有点挂了。 This fails with a bad return
: 这失败了, 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: 我也尝试将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
}
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? 如何实现@FunctionalInterface
或类似样式的闭包/ lambda,它不会尝试从定义它的函数 return
?
In Kotlin, return
statements inside lambdas work differently from those in Java. 在Kotlin中,lambda中的return
语句与Java中的return
语句不同。 If you write just return
, it means return from the innermost function declared with keyword fun
, and it ignores lambdas -- in your code, it means 'return from every
'. 如果只写return
,则表示从使用关键字fun
声明的最内层函数返回,它忽略lambda - 在代码中,它表示“从every
返回”。
To return from a lambda, use qualified return@label
-- in your case, it's return@Thread
(and return@Runnable
for the second example), like in this simplified snippet: 要从lambda返回,请使用限定的return@label
- 在您的情况下,它return@Thread
(并return@Runnable
作为第二个示例),就像在这个简化的片段中一样:
for (i in 1..4) {
Thread {
if (i % 2 == 0)
return@Thread
println("Thread $i")
}.run()
}
(runnable demo of this code) (此代码的runnable演示)
Also, there is a thread { ... }
function in kotlin-stdlib
that you might find useful (and, similarly, the return statement for its lambda is return@thread
). 此外,在kotlin-stdlib
中有一个thread { ... }
函数,您可能会发现它很有用(同样,其lambda的return语句是return@thread
)。
You can find a more detailed explanation in the language reference and in this answer . 您可以在语言参考和本答案中找到更详细的说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.