Remon Shehata
01/03/2022, 10:01 AMfun main() {
var text: String? = "hello"
text?.let {
print(text) // option 1
print(it) // option 2
}
}
Marko Novakovic
01/03/2022, 10:11 AMit
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 thatMax Ferrier
01/03/2022, 10:11 AMit
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.Marko Novakovic
01/03/2022, 10:12 AMtext
is still nullable inside let
Remon Shehata
01/03/2022, 10:16 AMMarko Novakovic
01/03/2022, 10:18 AMVampire
01/03/2022, 10:50 AMtext
change? let
is not executed asynchronouslyAlex
01/03/2022, 11:02 AMtext
might have been changed in another thread, no? You can not be sure it didn'tVampire
01/03/2022, 11:05 AMtext
.
In the example, both options are imho absolutely identical.Alex
01/03/2022, 11:08 AMfun main()
parts and the multithreading problem cannot be excluded anymore.Vampire
01/03/2022, 11:12 AMVampire
01/03/2022, 11:13 AMtext
can change asynchronously, it might not be.Remon Shehata
01/03/2022, 11:23 AMeygraber
01/03/2022, 4:50 PMtext
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=C0B8M7BUYVampire
01/03/2022, 4:55 PMDaniel B Duval
01/04/2022, 2:00 AMgildor
01/04/2022, 3:50 AM