Home > Mobile >  Android Kotlin callback with unkown number of arguments
Android Kotlin callback with unkown number of arguments

Time:11-30

i'm creating a function like this:

fun someFunction(
    callBack: () -> Unit
){
    callback.invoke()
}

when i will use the function:

someFunction(
    callBack = callBackFun()

)

So the question is, since i don't know, how many parameter callBackFun() will have(could be 0 or multiple) since someFunction could be use in multiple situation. how can i create the callback with 0 or more argument (vararg didn't work in this situation)

CodePudding user response:

You put callBackFun() inside two curly braces {} and you will be able to pass any function with different arguments:

someFunction(
    callBack = { callBackFun() }
)

someFunction(
    callBack = { secondCallBackFun(arg1, arg2) }
)

someFunction(
    callBack = { thirdCallBackFun(arg1, arg2, arg3) }
)

And you can even pass multiple functions and write any logic you want inside the lambda it's just like any other function:

someFunction(
    callBack = { 
        val arg1 = "test"
        val arg2 = "test2"
        val arg3 = 21

        callBackFun()
        secondCallBackFun(arg1, arg2)
        thirdCallBackFun(arg1, arg2, arg3)
    }
)

But callBack lambda function arguments should be known, you are setting its type as: () -> Unit so it's not taking any argument.

CodePudding user response:

Using vararg inside your callback function is not supported right now, you can use List if you like:

fun someFunction(
    callBack: (args: List<Any>) -> Unit
){
    callback.invoke(listOf<Any>())
}

CodePudding user response:

In kotlin you can provide several lambda function to higher order function with vararg, no problems with that. For example, like this:

fun myFunction(vararg func: () -> Unit) {
        //Something to do
}

You can use it as below:

myFunction(
  { TODO() }, 
  { TODO() }, 
  { TODO() }, 
)

Or even like this:

myFunction(
  func = arrayOf(
      { TODO() },
      { TODO() },
      { TODO() },
  )
)

UPD: If you want to provide by function name(like this:newFun()) you can consider also this:

myFunction(
    func = arrayOf(
        ::newFun,
        ::newFun2,
        ::newFun3,
    )
)

And of course:

myFunction(
    ::newFun,
    ::newFun2,
    ::newFun3,
)
  • Related