Kotlin - 替换 class 委托 - 具有相同功能不同签名的多个 classes

Kotlin - Replace class delegation - Multiple classes with same functionality different signature

我正在使用 JunitRules RuleChain 和 Kotlin。我对两者都不熟悉,有两个 classes 做完全相同的事情,唯一的区别是规则链。

第一个 class 看起来像这样:

class BaseActivityTestRule<T : Activity>(
    private val activityRule : ActivityRule<T>
) : TestRule by RuleChain.outerRule(CustomRuleOne).around(activityRule) {

    // do something 
}

我需要另一个 class,它做的事情与 BaseActivityTestRule 完全相同,但代表不同。

示例:

class ExtendedActivityTestRule<T : Activity>(
    private val activityRule : ActivityRule<T>
) : TestRule by RuleChain.outerRule(CustomRuleOne).around(CustomRuleTwo).around(activityRule) {

    // do something 
}

如何在不复制代码块的情况下完成此操作?

只需将一个布尔参数传递给您的构造函数并使用它来创建基本或扩展 TestRule:

fun <T> createTestRule(activityRule: ActivityRule<T>, extended: Boolean) = 
    if(extended) 
        RuleChain.outerRule(CustomRuleOne).around(CustomRuleTwo).around(activityRule)
    else
        RuleChain.outerRule(CustomRuleOne).around(activityRule)

class ActivityTestRule<T : Activity>(
    private val activityRule : ActivityRule<T>,
    extended: Boolean = false
) : TestRule by createTestRule(activityRule, extended) {

    // do something 
}

回答我自己的问题。我最终抽象了功能并创建了两个单独的 classes,它们具有扩展抽象 class 的不同签名。

示例:

abstract class BaseActivityTestRule<T : Activity>(
private val activityRule : ActivityRule<T>){  
 // Do Something 
}

然后扩展它:

class ExtendedActivityTestRule<T : Activity>(
private val activityRule : ActivityRule<T>): BaseActivityTestRule<T>(activityRule), TestRule by Delegate 

后续实施:

class DifferentActivityTestRule<T : Activity>(
private val activityRule : ActivityRule<T>): BaseActivityTestRule<T>(activityRule), TestRule by SomeOtherDelegate