Extend class primary constructor without repeating every single parameter

Hi, not sure if it is the correct category but it goes.

I found very frustrating the fact that I need to repeat all the parameters in the primary constructor in classes that descend from a complex class.

For example:

open class Bird(val name:String, val sound:Sound, val color:String = "black")

class Duck(name:String, sound:Sound, color:String = "black", val jumpHeight:Int):  Bird(name,sound,color)

This is one small example, with only one subclass, but you can see i repeated the same stuff 3 times already, quite annoying. This Specially affects big api response models.

My suggestion is make a new keyword for extending the primary cosntructor paramenters, like.

open class Bird(val name:String, val sound:Sound, val color:String = "black")

class Duck(..., val jumpHeight:Int): Bird(...)

or if “…” is not a good keyword maybe:

open Bird(val name:String, val sound:Sound, val color:String = "black")

class Duck extend constructor(val jumpHeight:Int): Bird()

Something like this would be really usefull.

Even simple languages like SQL allow this, I know it is quite different because it does not have constructors and methods but still, they thought about the time the developer would spend repeating fields.

CREATE TABLE birds (
  name text,
  sound text,
  color text
);

CREATE TABLE ducks (
  jumpHeight int
) INHERITS (birds);

Thank you for reading.

2 Likes

I like the use-case but I wonder if Decorators would pave a way for this or other function code.

For example, if we could generally reference functions (and this is only for making this example) using this@fun.
The ability to forward on params could be proposed using the spread operator like this: Using Bird(*this@fun)

class Duck(name:String, sound:Sound, color:String = "black", val jumpHeight:Int):  Bird(*this@fun)

Of course, this also includes the spread operator changes. I’m more wondering if there’s a more expandable form of syntax that could be in parity with future Kotlin features.
I’m not necessary advocating for those, or OPs proposal being done-- the use-case seems like a good thing to keep in mind.

1 Like

Could be, and could also be useful for using super functions when overriding from superclass