首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >defer()和defer{}之间的区别是什么

defer()和defer{}之间的区别是什么
EN

Stack Overflow用户
提问于 2021-08-05 13:43:10
回答 2查看 92关注 0票数 3

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-08-05 14:14:13

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

这里有一个重写代码的例子。

例如,给定以下函数:

代码语言:javascript
运行
复制
fun wrapFunctionCall(callback: (Int) -> Int) {
   println(callback(3))
}
代码语言:javascript
运行
复制
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

票数 4
EN

Stack Overflow用户

发布于 2021-08-05 13:54:31

这两个函数是相同的,不同之处在于Kotlin语法。

如果一个函数接收一个函数作为最后一个参数,它可以被传递到圆括号之外。详细信息请参见the documentationthis answer

然而,我不知道关于RxKotlin的细节。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68667754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档