Ivan Pavlukhin
Ivan Pavlukhin

Reputation: 190

Kotlin automatic derived class constructor with signature matching super class constructor

Sorry that I do not have practical example for such thing, but I am thinking about such feature from time to time. Here is my synthetic example:

abstract class Greeter(val firstName: String, val lastName: String) {
  abstract fun greet()
}

class Formal(firstName: String, lastName: String): Greeter(firstName, lastName) {
  override fun greet() {
    println("Hello $firstName $lastName!")
  }
}

class Informal(firstName: String, lastName: String): Greeter(firstName, lastName) {
  override fun greet() {
    println("Hi $firstName!")
  }
}

Here super class constructor is called explicitly by derived classes. Is it possible to do it automatically? The desired thing is to be able do something like:

class Informal(*): Greeter(*) {
  override fun greet() {
    println("Hi $firstName!")
  }
}

Which will generate derived class constructor with same signature as super class (primary) constructor and that constructor will just call super class (primary) constructor.

For me it is not a big problem to define derived class for the first time, but changing all derived classes when base class constructor is changed could be annoying.

Upvotes: 2

Views: 210

Answers (1)

yole
yole

Reputation: 97288

As of Kotlin 1.2.x, this is not possible. There is an open feature request for this functionality which is under consideration for future Kotlin versions.

Upvotes: 4

Related Questions