Transfer function as a parameter in Kotlin

I am trying to pass a function as a parameter, but it throws out "Unit cannot be called as a 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'
} 
+7
source share
4 answers

The problem is that you are not passing the function as a parameter to the method uploadImageToParse. You pass the result. In addition, the method uploadImageToParseexpects Unit tosafeCall be not a function.

To do this, you first need to declare an uploadImageToParseexpect function parameter.

fun uploadImageToParse(file: String?, saveCall: () -> Unit) {
    saveCall()
}

Then you can pass the parameters of the function to this method.

uploadImageToParse(imageFile, {saveCall()})

For more information about the topic, see Higher Order Functions and Lambdas in the Kotlin documentation.

: @marstran, , .

uploadImageToParse(imageFile, ::saveCall)
+21

:

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

() - .

-> Unit - .

:

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

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

. Kotlin

+3

-,
:

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)
}
+1

. . :

, :

fun uploadImageToParse(file: String?, saveCallParameter: (a:String,b:Int,c:String) -> Unit) {
saveCall(x,y,z) }

:

uploadImageToParse(saveCallParameter={a,b,c->saveCall(a,b,c)}

saveCall .

0
source

Source: https://habr.com/ru/post/1667941/


All Articles