https://kotlinlang.org logo
Title
l

Luke Sleeman

01/20/2020, 4:55 AM
// 1
something?.let { return it }
Or
// 2
if(something != null) { return something }
1️⃣ 5
2️⃣ 11
m

Mikael Alfredsson

01/20/2020, 7:06 AM
If
something
is mutable and accessible from other threads,
2
might still return null
a

arekolek

01/20/2020, 8:13 AM
won't smart-cast not be available in that case?
m

Mikael Alfredsson

01/20/2020, 8:16 AM
Smart cast to 'Int' is impossible, because 'something' is a mutable property that could have been changed by this time
(assuming
something
is an Int?) (so the compiler actually stops you from making this mistake)
e

Eduardo Pinto

01/21/2020, 7:29 AM
IMO I like the option 2 for being simpler for people that aren't kotlin developers. 99.999997% (made up stats) programming languages have a if statement.
c

Czar

01/28/2020, 5:29 PM
My commentary would be to refrain from multiple/short-circuiting returns. For me this would be prime example to use if as an expression: return
if (something == null) calculateAlternative() else something
Or even
return something ?: calculateAlternative()
e

Eduardo Pinto

01/30/2020, 9:43 AM
Lovely usage of the elvis operator.
g

gildor

05/04/2020, 9:45 AM
also for short expressions you can remove curly praces and option 2 becomes even shorter and more clean:
if (something != null) return something