Abhishek Pharasi
Abhishek Pharasi

Reputation: 11

Kotlin .let {} null safety

When using the .let { } function I noticed that when doing the following:

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

You have to guarantee safety for a bucket in this case i.e. bucket?. or bucket!! while null safety

Upvotes: 1

Views: 2725

Answers (4)

PrashanthR
PrashanthR

Reputation: 73

Because 'bucket' can be nullable variable there are different ways to make null safe calls in Kotlin, one of the standard method is using the 'let' function with safe call operator -'?'

So if you want to guarantee safety for a bucket in this case, it should be,

      bucket?.let { nullSafeBucket ->
        nullSafeBucket.assignedVariantName?.let { nullSafeAssignedVariantName ->
            nullSafeBucket.determineVariant() -- > bucket is null safe
            //assignedVariantName is as well null safe
        }
    }

}

Important to note - bucket!! will throw NPE if the value is null which will lead to a crash, hence it is not recommended unless 100% sure that the value is not null.

Upvotes: 0

Rahul Khurana
Rahul Khurana

Reputation: 8834

Kotlin .let{} method provides null safety

bucket?.assignedVariantName?.let { 
    // use `it` as non-null variable
    it.determineVariant()
}

You need to use it inside the let block to use it.

Upvotes: 2

Jeel Vankhede
Jeel Vankhede

Reputation: 12118

Standard function let() provides block as lambda method expression to callback on invocation. So, variable on which it's being called is passed as it in argument of block.

So, if you use it on safe call operator, it provides you non-null variable as it in callback. You can also rename it whatever you want like below :

bucket?.assignedVariantName?.let { 
    it.determineVariant() //<-- You can directly use it here
}

or rename it like anything:

bucket?.assignedVariantName?.let { name ->
    name.determineVariant() //<-- Renaming `it` to `name`
}

Upvotes: 2

Bach Vu
Bach Vu

Reputation: 2348

Since bucket is nullable, you don't need to call let on assignedVariantName, do it like this

bucket?.let { 
    it.determineVariant()
}

Upvotes: 5

Related Questions