Kotlin:我怎样才能避免构造函数中的代码重复?

Jir*_*ire 7 constructor code-duplication duplicates kotlin

通常我发现自己处于一种情况,我有一个具有许多可选参数的超类,并且这些相同的参数也需要在其子类中是可选参数.

例如,超类:

abstract class Plugin(val name: String, val version: String = "1.0",
                      val author: String = "", val description: String = "")
Run Code Online (Sandbox Code Playgroud)

扩展这个课程是一件痛苦的事.这是一个示例子类:

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)
Run Code Online (Sandbox Code Playgroud)

注意:我将用我的解决方案回答这个问题.我正在寻找更好的解决方案.

Jir*_*ire 6

我通常解决这个问题的方法是创建一个数据类来表示参数.

data class PluginInfo(val name: String, val version: String = "1.0",
                      val author: String = "", val description: String = "")
Run Code Online (Sandbox Code Playgroud)

然后我将此类作为构造函数中的参数.

abstract class Plugin(val info: PluginInfo)

abstract class CyclePlugin(info: PluginInfo, val duration: Int,
                           val durationUnit: TimeUnit = MILLISECONDS) : Plugin(info)
Run Code Online (Sandbox Code Playgroud)

然后可以像这样实现一个示例插件:

class ExamplePlugin : CyclePlugin(PluginInfo("Example Plugin", author = "Jire"), 8, TimeUnit.SECONDS)
Run Code Online (Sandbox Code Playgroud)


小智 5

@miensol一样,您可以在构造函数之外定义属性.

abstract class Plugin(val name: String) {

    open val version: String = "1.0"
    open val author: String = ""
    open val description: String = ""

}
Run Code Online (Sandbox Code Playgroud)

然后,您CyclePlugin只能使用必要的name参数进行定义:

abstract class CyclePlugin(name: String, val duration: Int,
                           val durationUnit: TimeUnit = MILLISECONDS) : Plugin(name)
Run Code Online (Sandbox Code Playgroud)

然后,例如,您可以覆盖以下字段ExamplePlugin:

class ExamplePlugin : CyclePlugin("Example Plugin", 8, TimeUnit.SECONDS) {

    override val author = "Giovanni"
    override val description = "This is an example plugin"

}
Run Code Online (Sandbox Code Playgroud)