How would I fix this code? I’d like `reportError()...
# announcements
e
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
if you don’t need to capture that
url
, why not just use if/else?
e
Oops, I oversimplified my code. I have edited it to add
it
.
a
This code will not compile if url is nullable
e
url
isn’t nullable, but
selectedTab
and
content
are.
l
I think you want
?.let
s
also true
a
If you don't do ?.let it will not compile
s
but also, still, if/else would work just fine here
👍 2
e
Thanks, @Luke. Could you explain why?
@Shawn Wouldn’t I have to save the argument to
doSomething()
somewhere?
s
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
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
Thanks, @Luke.
a
What's wrong with just doing
Copy code
val url = store.state.slectedTab?. content?.url
if (url != null) doSomething(url) 
else reportError...
👆 4
k
I like
Copy code
when(val url = store.state.slectedTab?. content?.url){
    null ->reportError()
    else -> doSomething(url) 
}
1
s
@Kroppeb nice work! the format looks cleaner to me (a happy coincidence that
null ->
and
else ->
line up 😃)