1

I am new to Kotlin and have managed to modify my Java timer class so that I can implement it with two lines of code.

I wonder if there is some way to perhaps modify it and so implement it with one line of code? Thanks for any suggestions.

Two lines implementation:

fun testTimer() {
    var tmr = MyTimer(1000, true)
    tmr.onTimer = { doSometing() }
}

Timer 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)
    }
}

2 Answers 2

3

You could do

val tmr = MyTimer(1000, true).apply {
    onTimer = { doSomething() }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your time in answering my question. This works for me, but I will probably use @marianosimone's answer in my final implementation
2

Given your interface, you can probably move your properties declaration to a primary constructor, and the start() to an init block.

Also note that val over var gives you 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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.