Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to inherit constructors in Kotlin?

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?

Edit

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.

like image 537
Pau Garcia Gozàlvez Avatar asked Apr 12 '19 08:04

Pau Garcia Gozàlvez


People also ask

Is it possible to inherit the constructor?

Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

Which inheritance is not supported in Kotlin?

In Kotlin we are not allowed to extend multiple superclasses. Multiple-inheritance is achieved by giving concrete functions to interfaces.

Does Kotlin have inheritance?

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.

How do you get inheritance in Kotlin?

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.


1 Answers

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, "")
like image 157
Alexey Romanov Avatar answered Nov 16 '22 00:11

Alexey Romanov