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

Shafayat Alam picture Shafayat Alam · May 29, 2017 · Viewed 12.1k times · Source

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?

Answer

hotkey picture hotkey · May 29, 2017

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() { /* ... */ }
}