defer() 和 defer{} 有什么区别

Sun*_*y13 3 kotlin rx-java rx-kotlin

defer() 我正在研究 RxKotlin,出现了一个问题:和 之间有什么区别defer{}

Vin*_*rat 5

defer()并且defer {}只是写同一件事的两种方式。Kotlin 在某些特定情况下允许使用一些快捷方式来帮助编写更具可读性的代码。

这是重写一些代码的示例。

例如,给出以下函数:

fun wrapFunctionCall(callback: (Int) -> Int) {
   println(callback(3))
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)

https://kotlinlang.org/docs/lambdas.html#function-types