Create an instance of an abstract class in Kotlin

Kotlin

Kotlin 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSloganhoView Question on Stackoverflow
Solution 1 - KotlinKota1921View Answer on Stackoverflow