我试图理解为什么需要 let。在下面的示例中,我有一个带有函数 giveMeFive 的类 Test:
public class Test() {
fun giveMeFive(): Int {
return 5
}
}
给定以下代码:
var test: Test? = Test()
var x: Int? = test?.giveMeFive()
test = null
x = test?.giveMeFive()
x = test?.let {it.giveMeFive()}
x 设置为 5,然后在 test 设置为 null 后,调用以下任一语句为 x 返回 null。鉴于在空引用上调用方法会跳过调用并将 x 设置为空,为什么我还需要使用 let?在某些情况下只是?行不通,需要 let 吗?
此外,如果被调用的函数没有返回任何内容,那么 ?.将跳过通话,我不需要?。让那里。
最佳答案
let()
fun <T, R> T.let(f: (T) -> R): R = f(this)
let() 是一个作用域函数:只要您想为代码的特定范围定义变量但不能超出范围,就可以使用它。让您的代码保持良好的独立性非常有用,这样您就不会“泄漏”变量:可以访问它们应该在的位置。
DbConnection.getConnection().let { connection ->
}
//连接在这里不再可见
let() 也可以用作针对 null 测试的替代方法:
val map : Map<String, Config> = ...
val config = map[key]
// config is a "Config?"
config?.let {
// This whole block will not be executed if "config" is null.
// Additionally, "it" has now been cast to a "Config" (no
question mark)
}
关于kotlin - 了解 Kotlin 的必要性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54382675/