Reputation: 381
I have a Parent
class which is extended by a lot of childs and I want to avoid to copy the long constructor in each of them because it is always the same.
open class Parent(arg1: Any, arg2: Any, arg3: Any...)
class ChildA(arg1: Any, arg2: Any, arg3: Any...): Parent(arg1, arg2, arg3...)
class ChildB(arg1: Any, arg2: Any, arg3: Any...): Parent(arg1, arg2, arg3...)
[...]
Is there a way to inherit the constructor or maybe a function implemented on the Parent
that instantiates a Child
class?
My expectation is to implement the Child
classes without having to define its constructor. The reason is that I have about 15 childs and each parameter have an optional value, so the resulting code is not so pretty.
Upvotes: 16
Views: 8446
Reputation: 170723
If it's always the same (or only extended), you can create a class for holding the parameters:
data class ConstructorParams(arg1: Any, arg2: Any, arg3: Any...)
open class Parent(params: ConstructorParams)
class ChildA(params: ConstructorParams) : Parent(params)
class ChildB(params: ConstructorParams, extraParam: Int) : Parent(params)
You could add to it a helper function to avoid explicit ConstructorParams
when instantiating the classes, but it has a performance trade-off (though this version won't work for Child2
):
inline fun <reified T : Parent> create(arg1: Any, arg2: Any, arg3: Any...) =
T::class.primaryConstructor.call(ConstructorParams(arg1, arg2, ...))
create<Parent>(1, 2, "")
Upvotes: 10