119

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() {

    }
};
iknow
  • 8,358
  • 12
  • 41
  • 68
Sloganho
  • 2,041
  • 3
  • 16
  • 20

2 Answers2

236

You can use this method:

var variableName = object: CountDownTimer(...){
    ...
}

These are called "object expressions" in Kotlin. The docs are available here: Object expressions

Ayush Shrestha
  • 194
  • 1
  • 7
Kota1921
  • 2,451
  • 1
  • 10
  • 13
-2

Just makes sure you have compatible data types

Mark S. Khalil
  • 113
  • 1
  • 4
  • This does not answer the question at all. OP asked about syntax to instantiate abstract classes. – Ercksen Nov 26 '22 at 16:02