我正在研究RxKotlin,出现了一个问题:defer()
和defer{}
之间的区别是什么
发布于 2021-08-05 14:14:13
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
}
发布于 2021-08-05 13:54:31
这两个函数是相同的,不同之处在于Kotlin语法。
如果一个函数接收一个函数作为最后一个参数,它可以被传递到圆括号之外。详细信息请参见the documentation和this answer。
然而,我不知道关于RxKotlin的细节。
https://stackoverflow.com/questions/68667754
复制相似问题