Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an instance of an abstract class in Kotlin

Tags:

kotlin

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() {      } }; 
like image 848
Sloganho Avatar asked Dec 07 '15 21:12

Sloganho


People also ask

How do you create an instance of a class in Kotlin?

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).

Can we create object of abstract class in Kotlin?

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.

Can not create instance of abstract class Kotlin?

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.

Can not create an instance of the abstract class or interface?

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.


1 Answers

You can use this method:

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

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

like image 56
Kota1921 Avatar answered Sep 28 '22 02:09

Kota1921