Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: 'This type has a constructor and thus must be initialized here', but no constructor is declared

Tags:

Recently started with Kotlin

According to Kotlin docs, there can be one primary constructor and one or more secondary constructor.

I don't understand why I see this error enter image description here

Since class test has no primary constructor.

This works fine:

open class test {
}

class test2 : test() {
}

And here is another difficulty I have faced, when I define a secondary constructor the IDE shows another error saying

Supertype initialization is impossible without primary constructor enter image description here

But in the previous working example, I did initialize it, yet it worked fine. What did I get wrong?

like image 786
Shafayat Alam Avatar asked May 29 '17 14:05

Shafayat Alam


People also ask

What is a constructor in Kotlin?

A Kotlin constructor is a special member function in a class that is invoked when an object is instantiated. Whenever an object is created, the defined constructor is called automatically which is used to initialize the properties of the class.

How do I declare a class in Kotlin?

To define a class in Kotlin, class keyword is used: class ClassName { // property // member function ... .. ... } Here, we defined a class named Lamp . The class has one property isOn (defined in same way as variable), and two member functions turnOn() and turnOff() .


1 Answers

You get this error because, even if you don't define a primary or a secondary constructor in a base class, there is still a default no-argument constructor generated for that class. The constructor of a derived class should always call some of the super constructors, and in your case there is only the default one (this is the constructor that you can call like test() to create an object of the class). The compiler and IDE force you to do that.


The super constructor rules complicate the matter to some degree.

If you define a secondary constructor in the derived class without defining the primary constructor (no parentheses near the class declaration), then the secondary constructor itself should call the super constructor, and no super constructor arguments should be specified in the class declaration:

class test2 : test { // no arguments for `test` here
    constructor(a: Int) : super() { /* ... */ }
}

Another option is define the primary constructor and call it from the secondary one:

class test2() : test() {
    constructor(a: Int) : this() { /* ... */ }
}
like image 129
hotkey Avatar answered Sep 19 '22 14:09

hotkey