我仍然是 Kotlin 的相对新手,经过一番挖掘后,无法解决看起来很简单的问题。对于下面的代码,编译器返回: 对于“function = PositiveButtonClick”和 function = negativeButtonClick”,功能“单位转换”被禁用
为什么?我需要做什么?
谢谢
called with MessageBox(context, "Hello Test", "My Message");
fun MessageBox(contxt: Context?, title: String, message: String): Boolean {
val builder = AlertDialog.Builder(contxt)
with(builder) {
setTitle(title)
setMessage(message)
setPositiveButton("YES", DialogInterface.OnClickListener(function = positiveButtonClick))
setNegativeButton("NO", DialogInterface.OnClickListener(function = negativeButtonClick))
show()
}
return false
}
val positiveButtonClick = { dialog: DialogInterface, which: Int -> Unit
Log.i("Dialog", "Yes")
}
val negativeButtonClick = { dialog: DialogInterface, which: Int -> Unit
Log.i("Dialog", "No")
}
Run Code Online (Sandbox Code Playgroud)
我在 Kotlin 文档(高阶函数和 lambda)中找到了答案,但只是偶然。示例代码中有一个注释行
// The last expression in a lambda is considered the return value:
Run Code Online (Sandbox Code Playgroud)
因此,只需将 Unit 添加为 lambda 中的最后一行即可通过强制返回 Unit 来解决问题
val positiveButtonClick = { dialog: DialogInterface, which: Int -> Unit
Log.i("Dialog", "Yes")
Unit
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1720 次 |
| 最近记录: |