Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending Class with Many Parameters

Tags:

kotlin

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 =)

like image 977
Peter Keefe Avatar asked May 06 '26 00:05

Peter Keefe


2 Answers

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)
like image 131
holi-java Avatar answered May 11 '26 14:05

holi-java


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.

like image 30
Bryan Avatar answered May 11 '26 15:05

Bryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!