gpt4 book ai didi

Kotlin .let {} null 安全大概是假错误

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

使用 .let { } 时功能我注意到,在执行以下操作时:

bucket?.assignedVariantName.let {
bucket?.determineVariant() <-- guarantee safety for bucket
}

在这种情况下,您必须保证桶的安全,即 bucket?.bucket!!而 null 安全已经通过使用 ?.let 得到保证。然后我在执行以下操作时注意到:
bucket?.assignedVariantName?.let { <-- added safety check for property 
bucket.determineVariant() <-- doesn't need to guarantee safety for bucket
}

虽然在存储桶的属性上使用 let 而不是直接在存储桶上使用,但我想知道这是故意的还是 Kotlin 插件中的错误(在这种情况下,我在 Android Studio 中遇到了这个问题)

附加信息是,在这种情况下,bucket 是 local val而assignedVariantName 是一个可为空的var。
val bucket: T? = ...

最佳答案

这是预期的行为。 .let { ... } function被定义为

inline fun <T, R> T.let(block: (T) -> R): R = block(this)
T可以是可空类型,并且 let可以在空接收器上调用, null.let { }是有效代码。

现在看一下这两个调用:
  • bucket?.assignedVariantName.let { ... } .

    在这里,let无论接收者是否bucket?.assignedVariantName 总是被调用是否为空。

    bucket?.assignedVariantName 时,可能会出现这种情况。为空,因为 bucket为空 -- 那么 null刚刚传入let ,而且绝对不安全使用bucketlet堵塞。

    (runnable example of the case)
  • bucket?.assignedVariantName?.let { ... }
    在这种情况下,let仅在接收者 bucket?.assignedVariantName 时调用不为空,要求 bucket不为空及其 assignedVariantName不为空。此要求使使用 bucket 变得安全内let堵塞。
  • 关于Kotlin .let {} null 安全大概是假错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43632547/

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