arist0v
arist0v

Reputation: 159

Android Kotlin callback with unkown number of arguments

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)

Upvotes: 2

Views: 278

Answers (2)

Mohamed Rejeb
Mohamed Rejeb

Reputation: 2629

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.

Upvotes: 3

Javlon
Javlon

Reputation: 1334

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>())
}

Upvotes: 0

Related Questions