Hey guys I'm checking if mutli global variables ar...
# kotlin-native
r
Hey guys I'm checking if mutli global variables are not null before calling a function like that
Copy code
varX?.let { varX ->
    varY?.let { varY ->
        foo(varX, varY)
    }
}
is there a better way to have this null safe and thread safe but in a cleaner look?
something like
Copy code
(varX, varY)?.let { varX, varY ->
    foo(varX, varY)
}
e
Why not just use a basic if check for that?
Copy code
if (varX != null && varY != null) {
    foo(varX, varY)
}
t
he specifically mentioned they are global, so you’d have to take them into a local scope first (which
let
also does for you)
👍 1
r
@Eryk Lepszy this is not thread safe
e
You're right, I missed that, sorry
🙌 1
t
@Raed Ghazal you can make an inline function that does this, I think I used the one in this answer some time: https://stackoverflow.com/a/35522422/2338613 no stdlib way I am aware of, let me know if you found one though
r
@Tijl Okay nice!
thats why I love kotlin will use this approach
thank you
You're right, I missed that, sorry
@Eryk Lepszy no worries, thanks for trying 😄
n
I find this simpler to read:
Copy code
val x = x ?: return
val y = y ?: return
foo(x, y)
r
also nice but you don't always want to call
return
and end the function
c
Copy code
varX?.to(varY)
  ?.takeIf { varY != null }
  ?.let { (varX, varY) -> foo(varX, varY) }
It's ugly though.
😂 2
r
staying with my original approach is much better man @CLOVIS 😂
y
the best approach for me is
Copy code
run {
    val x = x ?: return@run
    val y = y ?: return@run
    foo(x, y)
}
c
@y9san9 actually you don't need the variable shadowing:
Copy code
run {
  foo(x ?: return@run, y ?: return@run
}
That might be the shortest/cleanest way.
y
lol yes it is