Kotlin.let {} null security presumably false error
While using the function, .let { }
I noticed that when doing the following:
bucket?.assignedVariantName.let {
bucket?.determineVariant() <-- guarantee safety for bucket
}
You must ensure that the bucket is safe in this case, i.e. bucket?.
or bucket!!
, while null safety is already guaranteed with help ?.let
, then I noticed when I do the following:
bucket?.assignedVariantName?.let { <-- added safety check for property
bucket.determineVariant() <-- doesn't need to guarantee safety for bucket
}
While using let on the bucket property and not directly on the bucket, I'm wondering if this is intentional or a bug in the Kotlin plugin (in this case I ran into this in Android Studio)
Additional information that in this case bucket has a value local val
and the assigned VariantName is var.
val bucket: T? = ...
source to share
This is expected behavior. The function is defined as .let { ... }
inline fun <T, R> T.let(block: (T) -> R): R = block(this)
T
can be of type zero, or let
can be called on an empty receiver, null.let { }
is a valid code.
Now let's look at two calls:
-
bucket?.assignedVariantName.let { ... }
...It is
let
always called here regardless of whether the receiver isbucket?.assignedVariantName
null or not.There is a possible case where it
bucket?.assignedVariantName
is null, sincebucket
it is null - thennull
it is simply passed tolet
, and it is definitely not safe to usebucket
inside thelet
block. -
bucket?.assignedVariantName?.let { ... }
In this case
let
, only called if the receiver isbucket?.assignedVariantName
not null, requiring itbucket
not to be null but itsassignedVariantName
not null. This requirement allows for usebucket
inside a blocklet
.
source to share