Kotlin 创建一个 class 的实例并在一行代码中实现回调
Kotlin make an instance of a class and implement a callback in one line of code
我是 Kotlin 的新手,我已经设法修改了我的 Java 计时器 class 以便我可以用两行代码实现它。
请问有没有办法修改一下,一行代码实现?
感谢您的任何建议。
两行实现:
fun testTimer() {
var tmr = MyTimer(1000, true)
tmr.onTimer = { doSometing() }
}
计时器class
class MyTimer {
private var running = false
private var repeatDelayMS: Int = 0
private val handler = Handler()
var onTimer:()-> Unit = {}
private val runnable = object : Runnable {
override fun run() {
if (running) {
onTimer()
if (repeatDelayMS > 0)
handler.postDelayed(this, repeatDelayMS.toLong())
else
stop()
}
}
}
constructor(repeatDelayMS: Int, runOnCreate: Boolean) {
this.repeatDelayMS = repeatDelayMS
if (runOnCreate)
start()
}
fun start() {
running = true
handler.postDelayed(runnable, repeatDelayMS.toLong())
}
fun stop() {
running = false
handler.removeCallbacks(runnable)
}
}
鉴于您的接口,您可能可以将属性声明移至主构造函数,并将 start()
移至 init
块。
另请注意 val
超过 var
会得到 immutable/read-only properties
// this is not one line now, but just for formatting purposes ;)
fun testTimer() {
val timer = MyTimer(
repeatDelayMS = 1000,
runOnCreate = true,
onTimer = { doSomething() }
)
}
class MyTimer(
private var running: Boolean = false,
private val runOnCreate: Boolean,
private val repeatDelayMS: Int = 0,
private val handler: Handler = Handler(),
private val onTimer: () -> Unit = {}
) {
init {
if (runOnCreate) {
start()
}
}
// the rest is the same
}
你可以
val tmr = MyTimer(1000, true).apply {
onTimer = { doSomething() }
}
我是 Kotlin 的新手,我已经设法修改了我的 Java 计时器 class 以便我可以用两行代码实现它。
请问有没有办法修改一下,一行代码实现? 感谢您的任何建议。
两行实现:
fun testTimer() {
var tmr = MyTimer(1000, true)
tmr.onTimer = { doSometing() }
}
计时器class
class MyTimer {
private var running = false
private var repeatDelayMS: Int = 0
private val handler = Handler()
var onTimer:()-> Unit = {}
private val runnable = object : Runnable {
override fun run() {
if (running) {
onTimer()
if (repeatDelayMS > 0)
handler.postDelayed(this, repeatDelayMS.toLong())
else
stop()
}
}
}
constructor(repeatDelayMS: Int, runOnCreate: Boolean) {
this.repeatDelayMS = repeatDelayMS
if (runOnCreate)
start()
}
fun start() {
running = true
handler.postDelayed(runnable, repeatDelayMS.toLong())
}
fun stop() {
running = false
handler.removeCallbacks(runnable)
}
}
鉴于您的接口,您可能可以将属性声明移至主构造函数,并将 start()
移至 init
块。
另请注意 val
超过 var
会得到 immutable/read-only properties
// this is not one line now, but just for formatting purposes ;)
fun testTimer() {
val timer = MyTimer(
repeatDelayMS = 1000,
runOnCreate = true,
onTimer = { doSomething() }
)
}
class MyTimer(
private var running: Boolean = false,
private val runOnCreate: Boolean,
private val repeatDelayMS: Int = 0,
private val handler: Handler = Handler(),
private val onTimer: () -> Unit = {}
) {
init {
if (runOnCreate) {
start()
}
}
// the rest is the same
}
你可以
val tmr = MyTimer(1000, true).apply {
onTimer = { doSomething() }
}