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
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
But in the previous working example, I did initialize it, yet it worked fine. What did I get wrong?
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.
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() .
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() { /* ... */ }
}
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