?.let or ?.run, which is better?

You are overthinking this. The only difference between let and run is that one exposes the receiver as it and another as this. That’s it. Use whatever makes the most sense for your case.


@broot ya true actually but i got one thing is for null check let is better
runBlocking { launch { name?.run { println(name) delay(2000) println("name x-> $name") } } launch { name = null } }

The above code snippet will print name as null even after null check
but if you use let it will print the name

I was the one who overthought and confused :laughing:

This is because you use name from the outer scope instead of the copy stored as this. The same will happen if you use let and use name inside.

1 Like

Wait I thought this would reference the name itself so that is also a copy then what is the reason of having 2 functions so it means in every case we can use anything we want there is no difference ?

Yes, there is no functional difference. The only difference is how your code reads. Depending on the case you could prefer e.g. user.let { it.name } over the user.run { name }. In others the opposite. Even the name of the function could be the reason to choose one over another - just to make the code read closer to English.


@broot thanks for the reply cos I was overthinking cos in an interview I got asked this and they said there is so I was deep diving into this concept so there is no difference except code reading.