I have looked around a bit, and have found no good answer to my problem. On my app, I've got a timer. This timer stops on a click, and I would like to calculate a score based on the time left. I can use the "millisUntilFinished" to calculate the score, but I can't reused the score variable in my app. Could you please help me with the correct / best way to do this ? Below, my code:
var score: Long
val timer = object : CountDownTimer(20000, 1000) {
override fun onTick(millisUntilFinished: Long) {
timer.setText("" + millisUntilFinished / 1000)
score = millisUntilFinished / 1000
}
override fun onFinish() {
timer.setText("0");
}
}
timer.start()
When I try to use it later in my app, I get a " Variable 'score' must be initialized. " I've tried quite a few things but every time I end up not being able to reuse a variable initialized in an override fun.
Thanks for your help !
You may define it as lateinit var
or you should initialize it.
lateinit var score: Long
val timer = object : CountDownTimer(20000, 1000) {
override fun onTick(millisUntilFinished: Long) {
timer.setText("" + millisUntilFinished / 1000)
score = millisUntilFinished / 1000
}
override fun onFinish() {
timer.setText("0");
}
}
timer.start()
Note that lateinit
defines in class not in function. Or you can use this:
var score=0.toLong()
val timer = object : CountDownTimer(20000, 1000) {
override fun onTick(millisUntilFinished: Long) {
timer.setText("" + millisUntilFinished / 1000)
score = millisUntilFinished / 1000
}
override fun onFinish() {
timer.setText("0");
}
}
timer.start()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.