Create an instance of an abstract class in Kotlin
KotlinKotlin Problem Overview
I'm new to Kotlin and I'm trying to use it in my Android project. I have this code:
public var oneTouchTimer: CountDownTimer = CountDownTimer(500, 100) {
override fun onTick(l: Long) {
}
override fun onFinish() {
}
}
And it's throwing the error:
Cannot create an instance of an abstract class.
Basically I'm trying to create an instance of CountDownTimer and cannot figure out how to convert it to Kotlin.
Here is the code in Java:
CountDownTimer oneTouchTimer = new CountDownTimer(500, 100) {
@Override
public void onTick(long l) {
}
@Override
public void onFinish() {
}
};
Kotlin Solutions
Solution 1 - Kotlin
You can use this method:
var variableName = object: CountDownTimer(...){
...
}
These are called "object expressions" in Kotlin. The docs are available here: Object expressions