https://kotlinlang.org logo
#android
Title
# android
o

Ofir Bar

02/17/2020, 11:59 AM
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

Leon K

02/17/2020, 12:10 PM
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

Ofir Bar

02/17/2020, 12:17 PM
Exactly, thank you Leon @Leon K btw, what did you mean by
list
?
l

Leon K

02/17/2020, 12:19 PM
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

Ofir Bar

02/17/2020, 12:23 PM
Agree, I usually ask just to train the brain 🙂 Other developer might get depressed trying to read my code lol
3 Views