Kotlin:如何避免构造函数中的代码重复?

Kotlin: How can I avoid code duplication in constructors?

我经常发现自己有一个 superclass 有很多可选参数,而这些相同的参数也需要在它的 subclasses 中是可选参数。

例如超class:

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

扩展这个 class 很痛苦。这是一个例子 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)

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

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

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

然后我将此 class 作为构造函数中的参数。

abstract class Plugin(val info: PluginInfo)

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

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

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

@miensol所述,您可以在构造函数之外定义属性。

abstract class Plugin(val name: String) {

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

}

然后你可以定义 CyclePlugin 只有必要的 name 参数:

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

然后,例如,您可以覆盖 ExamplePlugin 的某些字段:

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

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

}