Kotlin 是否支持将自定义函数作为变量传递给另一个函数?
Does Kotlin support passng a custom function as a variable in another function?
我有一个 class 我需要将自定义函数传递给警报对话框,实际上是创建一个自定义回调函数
这是一些伪代码。
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) -> Unit
并像这样传递它们
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 中以小写开头。
我有一个 class 我需要将自定义函数传递给警报对话框,实际上是创建一个自定义回调函数
这是一些伪代码。
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) -> Unit
并像这样传递它们
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 中以小写开头。