I have a class called A:
open class A (a: String, b: String, c: String)
And a class B which extends A:
class B(a: String, b: String, c: String, d: String) : A(a, b, c)
My question is if there is a way to do something like this, to avoid declaring all the parameters of A within the B constructor:
class B(super, d:String) : A(super)
If not, there should be =)
When you meet this problem, you should ask yourself why such a class need many parameters/dependencies rather than find out the solution by language syntax. Maybe its responsibility is unclear.
IF there are many domain concepts mixed in a class, then you need to redesign your classes as below:
data class C(val a: String, val b: String, val c: String)
open class A(val c:C)
class B(c:C, val d: String) : A(c)
IF you found B not is-A A, then you must using composition rather than inheritance, for example:
open class A (a: String, b: String, c: String)
class B(val a:A, val d: String)
No, Kotlin does not contain any construct that allows you simplify constructor parameters that match the parameters of the superclass.
I don't think I agree that this should be a feature of the language, but I would recommend starting a conversation on YouTrack if you think it should be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With