我正在学习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
}