【发布时间】:2021-10-10 12:45:53
【问题描述】:
我正在研究 RxKotlin,问题出现了:defer() 和 defer{} 之间有什么区别
【问题讨论】:
我正在研究 RxKotlin,问题出现了:defer() 和 defer{} 之间有什么区别
【问题讨论】:
defer() 和 defer {} 只是写同一件事的两种方式。 Kotlin 在某些特定情况下允许使用一些快捷方式来帮助编写更具可读性的代码。
这是一个重写一些代码的例子。
例如给定以下函数:
fun wrapFunctionCall(callback: (Int) -> Int) {
println(callback(3))
}
wrapFunctionCall(x: Int -> {
x * x
})
// Most of the time parameter type can be infered, you can then let it go
wrapFunctionCall(x -> {
x * x
})
// Can omit parameter, and let it be name `it` by default
wrapFunctionCall({
it * it
})
// wrapFunctionCall accepts a lambda as last parameter, you can pull it outside the parentheses. And as this is the only parameter, you can also omit the parenthesis
wrapFunctionCall {
it * it
}
【讨论】:
两个函数都是一样的,区别在于Kotlin语法。
如果一个函数接收一个函数作为最后一个参数,它可以在括号外传递。详情请参阅the documentation 和this answer。
但是我不知道 RxKotlin 的详细信息。
【讨论】: