首页 > 解决方案 > 为 kotlin 扩展函数的基础对象附加上下文

问题描述

这个问题专门针对Android开发中使用的Kotlin扩展功能。

因此,Kotlin 为我们提供了将某些扩展行为添加到类中以扩展基于类行为的能力。

示例:(取自我当前的 Android 项目,用于 Espresso 测试中的 viewAssertion)

fun Int.viewInteraction(): ViewInteraction {
    return onView(CoreMatchers.allOf(ViewMatchers.withId(this), ViewMatchers.isDisplayed()))
}

在我的用例中,我可以像这样使用它:

R.id.password_text.viewInteraction().perform(typeText(PASSWORD_PLAIN_TEXT), pressDone())

一切都很好,除了这个扩展函数为所有Int对象提供了扩展行为,而不仅仅是 Android 中的 View ID,这一点都不好。

问题是是否有任何方法可以为此提供上下文Int,例如在 Android 中,我们在 Android 中为上述给定情况提供了@IdRes 支持注释?

标签: androidkotlinextension-function

解决方案


您无法区分资源中的 Int 和普通 Int。它是同一个类,您正在向所有 Int 类型的类添加扩展。

另一种方法是创建自己的 Int 包装器:

class IntResource(val resource: Int) {

    fun viewInteraction(): ViewInteraction {
        return onView(CoreMatchers.allOf(ViewMatchers.withId(resource), ViewMatchers.isDisplayed()))
    }
}

然后我们像这样:

IntResource(R.id.password_text).viewInteraction().perform(typeText(PASSWORD_PLAIN_TEXT), pressDone())

推荐阅读