在kotlin中作为参数传递函数
我试图传递一个函数作为参数,但它会抛出'单元不能作为函数调用。 提前致谢。
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' }
问题是,您没有将函数作为参数传递给uploadImageToParse
方法。 你正在传递结果。 另外uploadImageToParse
方法期望safeCall
是Unit参数不是函数 。
为了这个工作,你必须首先声明uploadImageToParse
以期望一个函数参数。
fun uploadImageToParse(file: String?, saveCall: () -> Unit) { saveCall() }
然后你可以传递函数参数给这个方法。
uploadImageToParse(imageFile, {saveCall()})
有关该主题的更多信息,请参阅Kotlin文档中的高阶函数和Lambdas 。
编辑:正如@marstran指出的,你也可以使用函数引用作为参数传递函数。
uploadImageToParse(imageFile, ::saveCall)
接受函数指针作为参数是这样做的:
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文档