Ral*_*kum 1 functional-programming kotlin
我有一个带有多个参数的函数。这些参数之一是
private fun mySpecialFunction(
variable1: Int,
onChanged: ((Int?) -> Unit)? = null
)
Run Code Online (Sandbox Code Playgroud)
稍后在函数中调用它,如下所示:
onChanged?.invoke(2)
Run Code Online (Sandbox Code Playgroud)
在上层调用站点上,它的调用方式如下:
mySpecialFunction(
variable1 = 1,
onChanged = {
// do something with the number invoked above
}
)
Run Code Online (Sandbox Code Playgroud)
在 Kotlin 中如何调用 onChange 的这种用法?
onChanged是一个可为空的高阶函数。?“((Int?) -> Unit) ”中的表示?的值onChanged可以为空。此外,它已被分配了默认值null,这意味着如果您不传递此参数的值,它将为空。
高阶函数的常用语法是(Args) -> ReturnType. 在您的情况下,onChanged采用可为空的 Int ( Int?) 作为参数,并且不返回任何内容,即 returns Unit。
onChanged?.invoke(2)意味着如果onChanged不为 null,则调用它并2作为参数传递。
mySpecialFunction(
variable1 = 1,
onChanged = {
// This section will get executed when the onChanged function is invoked. Here the passed `Int?` will be available as `it`
}
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
109 次 |
| 最近记录: |