Kotlin是否支持将自定义函数作为另一个函数中的变量传递?
我有一个类需要将自定义函数传递给警报对话框,实际上是创建一个自定义回调函数 这里有一些伪代码Kotlin是否支持将自定义函数作为另一个函数中的变量传递?,kotlin,function-pointers,Kotlin,Function Pointers,我有一个类需要将自定义函数传递给警报对话框,实际上是创建一个自定义回调函数 这里有一些伪代码 fun someFunction(v: View) { ... ShowPopup(name, "Title", {YesAction(v, "Test for yes action")},{NoAction(v, "Test for no action")}) ... } fun NoAction (v: View, msg: String) { SendMessage( v, ms
fun someFunction(v: View) {
...
ShowPopup(name, "Title", {YesAction(v, "Test for yes action")},{NoAction(v, "Test for no action")})
...
}
fun NoAction (v: View, msg: String) {
SendMessage( v, msg)
SomeCancelationFunction()
}
fun YesAction (v: View, msg: String) {
SendMessage(v, msg)
SomeYesAction()
}
fun SendMessage(v: View, msg: String) {
var snack = Snackbar.make(v, msg, Snackbar.LENGTH_LONG)
snack.show()
}
fun ShowPopup(msg: String,
title: String,
cbFuncYes: () - > Unit,
cbFuncNo: () - > Unit
) {
val dlgBldr = AlertDialog.Builder(this @MainActivity)
dlgBldr.setPositiveButton("YES", {_,_ -> ::cbFuncYes()})
dlgBldr.setNegativeButton("No", {_,_ -> ::cbFuncNo()})
dlgBldr.setTitle(title)
dlgBldr.setMessage(msg)
val dlgShow: AlertDialog = builder.create()
dlgShow.show()
}
我的目标是能够调用
ShowPopup()
函数,将一些函数作为变量传递给它,以便在警报对话框的设置pos/neg操作中使用。单向:
您可以将cbFuncYes
和cbFuncNo
的类型更改为(DialogInterface,Int)->单元
,并像这样传递它们
val dlgBldr = AlertDialog.Builder(this @MainActivity)
dlgBldr.setPositiveButton("YES", ::cbFuncYes)
dlgBldr.setNegativeButton("No", ::cbFuncNo)
::cbFuncYes
和::cbFuncNo
称为函数引用
另一种方式:
调用lambda中传递的lambda,其签名为setPositiveButton
和setNegativeButton
如下所示:
val dlgBldr = AlertDialog.Builder(this @MainActivity)
dlgBldr.setPositiveButton("YES", {_,_ -> cbFuncYes()})
dlgBldr.setNegativeButton("No", {_,_ -> cbFuncNo()})
注意:函数名以小写字母Kotlin开头。当然。你认为
cbFuncYes
和cbFuncNo
首先是什么?它们是传递的函数。太好了!谢谢我最后使用了你提供的替代方法。当我尝试在添加(DialogInterface,Int)->单元的函数中更改lambda时,我会在回调函数中得到一个错误,因为它使用的是(视图,字符串)
。再次感谢!我还能够重构所有函数。干杯