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

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

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

在这种情况下,你必须保证铲斗的安全性bucket?.bucket!! 而无效的安全已经通过使用?.let然后我注意到当做以下事情:

 bucket?.assignedVariantName?.let { <-- added safety check for property bucket.determineVariant() <-- doesn't need to guarantee safety for bucket } 

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

额外的信息是,在这种情况下桶是一个local val而assignedVariantName是一个可为空的var。

 val bucket: T? = ... 

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

 inline fun <T, R> T.let(block: (T) -> R): R = block(this) 

T可以是一个可为空的类型,并且可以在一个null接收者上调用, null.let { }是有效的代码。

现在看看这两个电话:

  • bucket?.assignedVariantName.let { ... }

    在这里,不管接收者是否被bucket?.assignedVariantName是否为null。

    bucket?.assignedVariantName为空时,由于bucket为null – 那么null才传入let ,因此在let块中使用bucket绝对不安全。

    (可运行的案例)

  • bucket?.assignedVariantName?.let { ... }

    在这种情况下,只有在接收方bucket?.assignedVariantName不为空时,才会调用let ,要求该bucket不为null,并且其assignedVariantName不为null。 这个要求使得在let块中使用bucket是安全的。