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

3

我正在学习RxKotlin,有一个问题: defer()defer{} 有什么区别?

2个回答

5

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
}

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


3

这两个函数是相同的,区别在于Kotlin语法。

如果一个函数最后一个参数是函数,那么该函数可以在括号之外传递。详情请参见文档此答案

不过我不清楚RxKotlin的细节。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接