I mean, I want use a default placeholder if either...
# android
o
I mean, I want use a default placeholder if either the passed string “currentUser?.firstName” or “currentUser?.lastName” to
getString()
is null. Can I use this with elvis? I couldn’t find a way (unless using if/else,etc, just exploring something more clean)
l
so what you're asking for is a way to do one elvis on a pair of nullable values, right? like use both if both are non-null, but use a default if any one is null. this is a currently unsolved problem (at least by the stdlib), where you do have to use some kind of
if
,
list
, or something. What you want is a function from pair of Nullable to Nullable pair. you can define something like this in kotlin yourself:
Copy code
fun <A, B> Pair<A?, B?>.liftNullability(): Pair<A, B>? = if (first != null && second != null) Pair(first!!, second!!) else null
👍 1
o
Exactly, thank you Leon @Leon K btw, what did you mean by
list
?
l
you could use lists containing your nullable values, then do the following:
Copy code
listOf(nullable1, nulalble2).all { it != null }.filterNotNull().let { values -> doSomething(values[0], values[1])}
but please never do this, it's inefficient and extremely error prone
👍 1
o
Agree, I usually ask just to train the brain 🙂 Other developer might get depressed trying to read my code lol