Home > OS >  How to automatically pass an argument to a function when it is called implicitly kotlin
How to automatically pass an argument to a function when it is called implicitly kotlin

Time:01-24

maybe I phrased my question a little strange, but something became interesting to me.

Let's imagine that I have some Extension function:

fun Int.foo() {
    TODO()
}

Suppose that I need to pass the context of the Fragment from which I call it to this function, in which case I would do it like this:

fun Int.foo(context: Context) {
    TODO()
}

Here we are explicitly passing the Context of our Fragment to the function. However, I'm interested in the question - is it possible to somehow change this function so (or can it be called in some other way) so that I do not have to explicitly pass the Context?

I understand that I could do like this:

fun Fragment.foo() {
    var context = this.context
}

...however, I need an Extension function just above Int, so this method is not suitable.

Are there any ways how this can be done?

CodePudding user response:

I guess you're looking for context-dependent declarations that let you combine multiple receiver scopes:

context(Fragment)
fun Int.foo() {
    check(context != null) // context is actually Fragments context
}

Keep in mind however this feature is still in experimental state so it requires opt in by adding -Xcontext-receivers to your compiler options.

CodePudding user response:

The Int class is just a class for op with numbers It doesn't make sense to contain a Context object It is not possible to get context without passing it to the function There are other ways, which is to create a static object for the application class for example

class App : Application() {


companion object {
    var app: App? = null
}

init {
    app = this;
}

}

and then

fun Int.foo(){
    val context=App.app
    ...
}
  • Related