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? = ...

      

+3


source to share


1 answer


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 is bucket?.assignedVariantName

    null or not.

    There is a possible case where it bucket?.assignedVariantName

    is null, since bucket

    it is null - then null

    it is simply passed to let

    , and it is definitely not safe to use bucket

    inside the let

    block.

    (runnable case example)

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

    In this case let

    , only called if the receiver is bucket?.assignedVariantName

    not null, requiring it bucket

    not to be null but its assignedVariantName

    not null. This requirement allows for use bucket

    inside a block let

    .

+15


source







All Articles