Search code examples
androidkotlinextension-function

Attach context for base object of kotlin extension function


This question is specific for extension function of Kotlin used in Android development.

So Kotlin provides us capability to add certain extension behavior in to a class to extend the based class behavior.

Example: (take from my current Android project, for viewAssertion in testing with Espresso)

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

In my usecase, I can use it like:

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

All good, except this extension function gives the extended behavior to all Int objects, not just the View IDs in Android, which is not good at all.

The question is if there is any way to give context for this Int, like in Android we have @IdRes in Android support annotation for such given case above?


Solution

  • You can't differentiate between an Int from the resources and a normal Int. It is the same class and you are adding an extension to all the classes of the Int type.

    An alternative could be to create your own wrapper of Int:

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

    And then us it like this:

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