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() { } };
Similar to using the fun keyword in Kotlin to create a new function, use the class keyword to create a new class. You can choose any name for a class , but it is helpful if the name indicates what the class represents. By convention, the class name is written in Upper Camel Case (also called Pascal Casing).
Like Java, abstract keyword is used to declare abstract classes in Kotlin. An abstract class cannot be instantiated (you cannot create objects of an abstract class). However, you can inherit subclasses from can them.
In Kotlin, we cannot create an instance of an abstract class. Abstract class could only be inherited by a class or another Abstract class. So, to use abstract class, create another class that inherits the Abstract class.
No, you cannot create an instance of an abstract class because it does not have a complete implementation. The purpose of an abstract class is to function as a base for subclasses. It acts like a template, or an empty or partially empty structure, you should extend it and build on it before you can use it.
You can use this method:
var variableName = object: CountDownTimer(...){ ... }
These are called "object expressions" in Kotlin. The docs are available here: Object expressions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With