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.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
In Kotlin we are not allowed to extend multiple superclasses. Multiple-inheritance is achieved by giving concrete functions to interfaces.
In Kotlin, it is possible to inherit class properties and functions from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class. superclass (parent) - the class being inherited from.
Everything in Kotlin is by default final, hence, we need to use the keyword open in front of the class declaration to make it inheritable for other classes. Kotlin uses operator ":" to inherit a class.
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, "")
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