jay shah
06/16/2022, 11:29 AM?.let
and ?:
are thread safe? because using if
gives me smart cast errorgildor
06/17/2022, 9:25 AMgildor
06/17/2022, 9:32 AMif
under the hood. So they do not add or remove any thread safety, it depends on how you use itJoost Klitsie
06/17/2022, 11:06 AMval 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:
println(myNumber) // prints 4
println(myNumber) // prints 8
so naturally, if you do this:
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:
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):
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
}