Kotlin: How can I avoid duplicating code in constructors?

Often I find myself in a situation where I have a superclass that has many optional parameters, and the same parameters should also be optional parameters in their subclasses.

For example, a superclass:

abstract class Plugin(val name: String, val version: String = "1.0", val author: String = "", val description: String = "") 

Extending this class is pain. Here is an example of a subclass:

 abstract class CyclePlugin(name: String, version: String = "1.0", author: String = "", description: String = "", val duration: Int, val durationUnit: TimeUnit = MILLISECONDS) : Plugin(name, version, author, description) 

Note: I will answer this question with my decision. I am looking for a better solution.

+7
constructor duplicates kotlin code-duplication
source share
2 answers

As @miensol mentions, you can define your properties outside of the constructor.

 abstract class Plugin(val name: String) { open val version: String = "1.0" open val author: String = "" open val description: String = "" } 

Then you can define CyclePlugin only with the necessary parameter name :

 abstract class CyclePlugin(name: String, val duration: Int, val durationUnit: TimeUnit = MILLISECONDS) : Plugin(name) 

Then, for example, you can override some fields for ExamplePlugin :

 class ExamplePlugin : CyclePlugin("Example Plugin", 8, TimeUnit.SECONDS) { override val author = "Giovanni" override val description = "This is an example plugin" } 
+5
source share

I usually solve this problem by creating a data class to represent the parameters.

 data class PluginInfo(val name: String, val version: String = "1.0", val author: String = "", val description: String = "") 

Then I take this class as a parameter in the constructors.

 abstract class Plugin(val info: PluginInfo) abstract class CyclePlugin(info: PluginInfo, val duration: Int, val durationUnit: TimeUnit = MILLISECONDS) : Plugin(info) 

Then, an example plugin can be implemented as follows:

 class ExamplePlugin : CyclePlugin(PluginInfo("Example Plugin", author = "Jire"), 8, TimeUnit.SECONDS) 
+5
source share

All Articles