So both `?.let` and `?:` are thread safe? because ...
# android
j
So both
?.let
and
?:
are thread safe? because using
if
gives me smart cast error
🧵 2
g
Please, use threeads
And both of those checks are exactly the same as
if
under the hood. So they do not add or remove any thread safety, it depends on how you use it
j
You have a variable field (which means it can vary its value 😄 ) so between the lines, it could return different values. We can demonstrate this if we use a variable without backing field:
Copy code
val myNumber: Int
    get() = Random(<SEED>).nextInt(0, 10)
This will when you call
myNumber
return a random number so this shows, that if you for example do this:
Copy code
println(myNumber) // prints 4
println(myNumber) // prints 8
so naturally, if you do this:
Copy code
if (myNumber < 5) {
    println("$myNumber is smaller than 5!" // This might be not true
}
BUT if you wish to fix this, you should assign a variable first to hold the current value and after that do the calculation:
Copy code
val theNumber = myNumber
if (theNumber < 5) {
    println("$theNumber is smaller than 5!") // This does what you expect
}
this is what
.let
does under the hood, it assigns the value and then runs a check on that value (and not on the original variable):
Copy code
var myNullableString: String? = null

if (myNullableString != null) {
    // myNullableString could be null again here :(
}
val fixedNullableString = myNullableString
if (fixedNullableString != null) {
    // we can now mess around with fixedNullableString
}
myNullableString?.let { fixedNullableString ->
    // myNullableString could be null here, but fixedNullableString is definitely not null here
}
☝️ 1