Converting Thread/Runnable implementation from Java to Kotlin
我有一个现有的Java类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
我正在尝试将其转换为Kotlin。我对Runnable的闭合有点挂了。这会因错误的
而失败
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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退出,以帮助自己分离事物,但这也以相同的方式失败:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 } |
如何实现一个
在Kotlin中,lambda内的
要从lambda返回,请使用合格的
(此代码的可运行演示)
此外,您可能会发现
您可以在语言参考和此答案中找到更详细的解释。