https://kotlinlang.org logo
#announcements
Title
# announcements
e

Ellen Spertus

11/07/2019, 8:20 PM
How would I fix this code? I’d like
reportError()
to be called if the value preceding
let
is `null`:
Copy code
store.state.selectedTab?.content?.url.let {
     doSomething(it)
 } ?: run {
     reportError("Unable to get URL to send")
 }
Assume that both
doSomething()
and
reportError()
are void.
s

Shawn

11/07/2019, 8:21 PM
if you don’t need to capture that
url
, why not just use if/else?
e

Ellen Spertus

11/07/2019, 8:21 PM
Oops, I oversimplified my code. I have edited it to add
it
.
a

Anastasia Finogenova

11/07/2019, 8:22 PM
This code will not compile if url is nullable
e

Ellen Spertus

11/07/2019, 8:22 PM
url
isn’t nullable, but
selectedTab
and
content
are.
l

Luke

11/07/2019, 8:22 PM
I think you want
?.let
s

Shawn

11/07/2019, 8:23 PM
also true
a

Anastasia Finogenova

11/07/2019, 8:23 PM
If you don't do ?.let it will not compile
s

Shawn

11/07/2019, 8:23 PM
but also, still, if/else would work just fine here
👍 2
e

Ellen Spertus

11/07/2019, 8:23 PM
Thanks, @Luke. Could you explain why?
@Shawn Wouldn’t I have to save the argument to
doSomething()
somewhere?
s

Shawn

11/07/2019, 8:24 PM
you would, but imo that’s not such a big deal
also, the result of a safe-navigation call is always nullable, so you’ll need to keep using
?.
as you navigate through the structure
l

Luke

11/07/2019, 8:25 PM
let
is callable on nullables.
store.state.selectedTab?.content?.url
returns null if any call return null, in which case
it
is null inside
let{}
.
run
is never called
💯 1
by adding ? before
let
, you don’t call it if no url can be found
e

Ellen Spertus

11/07/2019, 8:26 PM
Thanks, @Luke.
a

Alowaniak

11/07/2019, 9:02 PM
What's wrong with just doing
Copy code
val url = store.state.slectedTab?. content?.url
if (url != null) doSomething(url) 
else reportError...
👆 4
k

Kroppeb

11/08/2019, 12:42 AM
I like
Copy code
when(val url = store.state.slectedTab?. content?.url){
    null ->reportError()
    else -> doSomething(url) 
}
1
s

Stephan Schroeder

11/08/2019, 10:02 AM
@Kroppeb nice work! the format looks cleaner to me (a happy coincidence that
null ->
and
else ->
line up 😃)