Search code examples
androidkotlinkotlin-extension

pass function with parameters in extension function(kotlin)


  • I am trying to create an Extension function in android with Handlers but facing issue:

Extension fun Code:

fun delayTask(millis: Long, myFunction: (data:String) -> Unit) {
    Handler().postDelayed({
        myFunction(data)    //why error is of data here
    }, millis)
}

Calling like this:

 delayTask(500, ::function)
  • Getting error Unresolved reference: data

Solution

  • data is not a parameter of your higher order function. It is a parameter of your function parameter. So it doesn't exist for you to pass to the passed function.

    To be able to pass this data to your lambda, you will need to add it as another parameter:

    fun delayTask(millis: Long, data: String, myFunction: (String) -> Unit) {
        Handler().postDelayed({
            myFunction(data)
        }, millis)
    }
    

    And when you call it, you would have to also pass the data:

    delayTask(500, someDataString, ::function)
    

    Your function could be more versatile by removing the parameter from the function parameter. Then you could call any function with any amount of parameters needed just by wrapping it in a lambda:

    fun delayTask(millis: Long, myFunction: () -> Unit) {
        Handler().postDelayed({
            myFunction()
        }, millis)
    }
    
    delayTask(500) { myFunction(someData) }
    

    For performance reasons, it would be better to make it inline. But the passed function has to be crossinline since it's wrapped in another object and called later:

    inline fun delayTask(millis: Long, crossinline myFunction: () -> Unit) {
        Handler().postDelayed({
            myFunction()
        }, millis)
    }
    

    Note this functionality is already available with the postDelayed function in Android Ktx core:

    Handler().postDelayed(500L) { someFunction() }