Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing function as parameter in kotlin

Tags:

kotlin

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'
} 
like image 221
Sai Avatar asked Jan 27 '17 05:01

Sai


People also ask

Can I pass a function as a parameter in Kotlin?

Kotlin gives us the power to declare high-order functions. In a high-order function, we can pass and return functions as parameters.

How do you pass parameters in Kotlin?

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.

How do you pass the lambda function as a parameter in Kotlin?

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.

How do you assign a function to a variable in Kotlin?

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.


1 Answers

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)
like image 176
Januson Avatar answered Oct 18 '22 08:10

Januson