Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't compile internal constructor call cause:Primary constructor call expected

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?

like image 597
Chriss Avatar asked Oct 23 '18 11:10

Chriss


People also ask

How do I make a secondary constructor in Kotlin?

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.

Can we have multiple constructors in Kotlin?

A Kotlin class can have a primary constructor and one or more additional secondary constructors.

Why does kotlin need a secondary constructor?

Secondary constructors allow initialization of variables and allow to provide some logic to the class as well. They are prefixed with the constructor keyword.


1 Answers

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)

like image 122
Bartek Lipinski Avatar answered Sep 28 '22 04:09

Bartek Lipinski