I'm trying to pass a function as a parameter but it throws 'Unit cannot be invoked as function. Thanks in advance.
uploadImageToParse(imageFile, saveCall1())
uploadImageToParse(imageFile, saveCall2())
uploadImageToParse(imageFile, saveCall3())
private fun uploadImageToParse(file: ParseFile?, saveCall: Unit) {
saveCall()//Throws an error saying 'Unit cannot be invoked as function'
}
Kotlin gives us the power to declare high-order functions. In a high-order function, we can pass and return functions as parameters.
In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T> ) inside the function body.
In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas. Frequently, lambdas are passed as parameter in Kotlin functions for the convenience.
You can assign them to variables and constants just as you can any other type of value, such as an Int or a String . This function takes two parameters and returns the sum of their values. Here, the name of the variable is function and its type is inferred as (Int, Int) -> Int from the add function you assigned to it.
Problem is, that you are not passing a function as a parameter to the uploadImageToParse
method. You are passing the result. Also uploadImageToParse
method is expecting safeCall
to be Unit parameter not a function.
For this to work you have to first declare uploadImageToParse
to expect a function parameter.
fun uploadImageToParse(file: String?, saveCall: () -> Unit) {
saveCall()
}
Then you can pass function parameters to this method.
uploadImageToParse(imageFile, {saveCall()})
For more information on the topic take a look at Higher-Order Functions and Lambdas in the Kotlin documentation.
Edit: As @marstran pointed out, you can also pass the function as a parameter using Function Reference.
uploadImageToParse(imageFile, ::saveCall)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With