首页 文章

在kotlin中传递函数作为参数

提问于
浏览
7

我正在尝试将函数作为参数传递,但它抛出'Unit不能作为函数调用 . 提前致谢 .

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'
}

3 回答

  • 3

    问题是,您没有将函数作为参数传递给 uploadImageToParse 方法 . 你传递的结果 . 另外 uploadImageToParse 方法期望 safeCallUnit 参数而不是 function .

    为此,您必须首先声明 uploadImageToParse 以期望函数参数 .

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

    然后,您可以将函数参数传递给此方法 .

    uploadImageToParse(imageFile, {saveCall()})
    

    有关该主题的更多信息,请参阅Kotlin文档中的Higher-Order Functions and Lambdas .

    编辑:正如@marstran指出的那样,您也可以使用Function Reference将该函数作为参数传递 .

    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 Documentation

  • 0

    使用lambda表达式,我们可以将方法作为参数传递
    例:

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

相关问题