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

Viewed 5379

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?

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)

Related