Travis Griggs
04/15/2021, 3:49 PMsomeNullableExpression?.let { thing -> thing.doStuff() } ?: run { otherwiseBehavior() }
a widely used pattern in Kotlin? I've been using it quite a bit when I port Swift code, because it's the closest (I thought) equivalent to Swift's if let thing = someNilableExpression { thing.doStuff } else { otherwiseBehavior()
. But I've found edge cases where there are surprises, and so I've been rethinking whether I should be using it so much.Adam Powell
04/15/2021, 3:59 PMdiesieben07
04/15/2021, 4:00 PMval thing = someNullableExpression()
if (thing != null) { thing.doStuff() } else { otherwiseBehavior() }
Adam Powell
04/15/2021, 4:00 PMthing
being in the surrounding scopeAdam Powell
04/15/2021, 4:01 PMwhen (val foo = expression()) {
is probably the closest analog in terms of that scopingdiesieben07
04/15/2021, 4:02 PMsomeNullableExpression().let { thing ->
if (thing != null) { thing.doStuff() } else { otherwiseBehavior() }
}
And then thing
is contained within the let.Adam Powell
04/15/2021, 4:06 PMAdam Powell
04/15/2021, 4:07 PMTravis Griggs
04/15/2021, 4:10 PMTravis Griggs
04/15/2021, 4:13 PMTravis Griggs
04/15/2021, 4:14 PMNir
04/15/2021, 4:15 PMNir
04/15/2021, 4:16 PMsomeNullableExpression.run {
if (it == null) ...
else ....
}
Nir
04/15/2021, 4:16 PMNir
04/15/2021, 4:17 PMthing
that is accessible throughout the function, and you clearly show exactly where the result of the expression is being used, without trying to stuff everything into one lineNir
04/15/2021, 4:18 PMvar
for example then this will sometimes cause smart casting to fail, since the variable could have been nulled in the meanwhileTravis Griggs
04/15/2021, 4:26 PMNir
04/15/2021, 4:38 PMNir
04/15/2021, 4:38 PMNir
04/15/2021, 4:38 PMTravis Griggs
04/15/2021, 4:46 PMNir
04/15/2021, 4:50 PMNir
04/15/2021, 4:51 PMgetSomething()?.let { transform(it) } ?: defaultValue
is completely fineTravis Griggs
04/15/2021, 4:57 PMNir
04/15/2021, 4:57 PMNir
04/15/2021, 4:59 PMwhen
argument is really the best alternative hereNir
04/15/2021, 5:01 PMletElse
function I think:
someExpression?.let {
...
} letElse {
...
}
Or something like that. Perhaps write your own ifNull
and ifNullElse
. But obviously you'd question whether it was worth it to introduce this.Nir
04/15/2021, 5:02 PMifNotNull
I suppose 🙂Adam Powell
04/15/2021, 5:06 PMnull
with the "take the else branch" directiveAdam Powell
04/15/2021, 5:07 PMletElse
infix functionAdam Powell
04/15/2021, 5:08 PM#define BEGIN {
#define END }
Nir
04/15/2021, 5:11 PMNir
04/15/2021, 5:11 PMNir
04/15/2021, 5:12 PMTravis Griggs
04/15/2021, 5:26 PM