Hi, is there a difference between those 2 options ...
# android
r
Hi, is there a difference between those 2 options here:
Copy code
fun main() {
    var text: String? = "hello"
    text?.let { 
        print(text) // option 1
        print(it) // option 2
    }
}
m
yes there is
it
is encapsulated in
let
block which means that no matter if
text
change
it
will be the same as when you called
.let
.
text
is not safe to use like that
👍 2
1
🤝 1
m
Both will work, but
it
represents the value you have tested and is safe. Your
text
variable is a
var
, so it can be modify elsewhere and crash while you use it.
👍 1
🙏 1
m
and
text
is still nullable inside
let
1
☝🏻 1
👍 2
r
Thanks Marko.
m
you’re welcome
v
How can
text
change?
let
is not executed asynchronously
a
text
might have been changed in another thread, no? You can not be sure it didn't
v
If it is multi-threaded and some other thread might change
text
. In the example, both options are imho absolutely identical.
a
It would be nice to clarify this to Remon, right? Even if the example given will not run into this problem. Just leave out the
fun main()
parts and the multithreading problem cannot be excluded anymore.
v
We just did, didn't we? 🙂
🤝 2
As posted it is the same, if
text
can change asynchronously, it might not be.
r
Thanks guys, I knew that it’s not thread safe. but it’s nice to say that here so if anyone else reads the chat thread they would know.
e
I'm 99% sure this isn't true, and that
text
would be smart cast to not null. I believe the reason is because the scope of
text
wouldn't allow anyone to modify it before that block is run. I think Kotlin does analysis to determine if it is captured in a scope that could modify it in another thread, and if it isn't then it does the smart cast. https://kotlinlang.slack.com/archives/C0B8M7BUY/p1641204754087000?thread_ts=1641204105.086400&cid=C0B8M7BUY
v
Here the missing percent 🙂
2
🔥 2
💯 2
✌️ 2
d
You'd want to use it as a general convention. If you expand this to an object where you use a getter for a value, the compile will fail due to not being able to smart cast. This will lead to a lot of extra boiler plate and/or null checks the let got you.
g
I would also recommend to use #getting-started channel for those questions, it’s not related on Android specifically