Passing function as parameter in kotlin

Accepting a function pointer as a parameter is done like this:

private fun uploadImageToParse(file: ParseFile?, saveCall: () -> Unit){
    saveCall.invoke()
}

The () are the types of the parameters.

The -> Unit part is the return type.

Second Example:

fun someFunction (a:Int, b:Float) : Double {
    return (a * b).toDouble()
}

fun useFunction (func: (Int, Float) -> Double) {
    println(func.invoke(10, 5.54421))
}

For more information, refer to the Kotlin Documentation


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)

Using lambda expression, We can pass method as parameters
Example:

fun main(args: Array<String>) {
  MyFunction("F KRITTY", { x:Int, y:Int -> x + y })
}

fun MyFunction(name: String , addNumber: (Int , Int) -> Int) {
  println("Parameter 1 Name :" + name)
  val number: Int = addNumber(10,20)
  println("Parameter 2 Add Numbers : " + number)
}

Tags:

Kotlin