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

13,608

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() { /* ... */ }
}
Share:
13,608

Related videos on Youtube

Shafayat Alam
Author by

Shafayat Alam

Attire - Fast, SEO Friendly Multipurpose WordPress Theme Love to code, learning new programming languages, and playing FPS games :p. Currently working with NodeJS, MongoDB, Android, and WordPress. Also worked with PHP, HTML, CSS, and Cordova.

Updated on August 21, 2020

Comments

  • Shafayat Alam
    Shafayat Alam over 3 years

    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?