Automatic constructor

When you have a super class with many constructor arguments, it becomes tedious to repeat the constructor in all implementing classes. It would be ideal for Kotlin to create a constructor automatically. Instead of:

class Impl(a: Int, b: Int, c: Int) : Super(a, b, c)

It could allow:

class Impl : Super // Automatically creating constructor for Impl based of Super

Impl(1, 2, 3)

Now this idea can be expanded for flexibility by allowing the override of individual constructor arguments, while for every argument not overridden, the argument would be generated:

class Impl(custom: String) : Super(b = custom.toInt())

Impl("2", 1, 3)

However, an important decision here would be order. Should it generate Impl(β€œ2”, 1, 3), respecting the order of the constructor, or Impl(1, β€œ2”, 3), respecting the order of the super constructor?

Once all arguments are specified, the auto constructor generator would not be used, as all arguments would be exhausted. Usage is as current:

class Impl(custom: Int) : Super(custom, custom, custom)

Impl("2")

Secondary constructors could follow the same idea:

class C(a: Int, b: Int) {
 constructor(custom: String) : this(custom.toInt())
}

C("1", 2)

If Super has a secondary constructor, the primary constructor can be used by default. A secondary constructor can also be generated for Impl. However, here a lot of ambiguity is introduced, so a new syntax would probably be good, but it could also be overspecialized.

I think having it automatically generate a constructor with the exact same arguments is a nice quality of life feature that would be pretty easy to implement. HOWEVER, once you get to modifying some of the arguments, I think you should have to create the constructor yourself. I don’t like the magic of having some arguments be required but not visible in the source code, and it also seems like it’d be very complicated to implement in the compiler.

1 Like