gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:24:06 31 4
gpt4 key购买 nike

我正在研究 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
}

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

关于kotlin - defer() 和 defer{} 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68667754/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com