Assume we have the following primary and secondary constructors:
open class Animal(val name:String){
internal constructor(message:InputStream): this(readName(message))
}
Why is not possible to call the internal constructor of the super class?
class Dog(name:String):Animal(name){
internal constructor(message:InputStream):super(message)
^^^^^
Primary constructor call expected
}
edit
Obviously it compiles when the primary constructor is converted to a secondary constructor or removed at all.
class Dog:Animal{
constructor(name:String):super(name)
internal constructor(message:InputStream):super(message)
}
Is this a compiler bug?
To do so you need to declare a secondary constructor using the constructor keyword. If you want to use some property inside the secondary constructor, then declare the property inside the class and use it in the secondary constructor. By doing so, the declared variable will not be accessed inside the init() block.
A Kotlin class can have a primary constructor and one or more additional secondary constructors.
Secondary constructors allow initialization of variables and allow to provide some logic to the class as well. They are prefixed with the constructor keyword.
From docs:
If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor(s). Delegation to another constructor of the same class is done using the
this
keyword
and:
If the class has no primary constructor, then each secondary constructor has to initialize the base type using the
super
keyword, or to delegate to another constructor which does that.
Your Dog
class has a primary constructor, so you have to delegate to that using this
.
If you remove the primary constructor, you will be able to refer to super
constructor:
class Dog : Animal {
constructor(message: InputStream) : super(message)
}
(the above raises no error)
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