Trying to concatenate a firstName + middle + last ...
# getting-started
c
Trying to concatenate a firstName + middle + last name. Only including a space between the values if they're not blank, and trying to not have double spaces between first and last if there is no middle name. Is there some std lib function for this? Or am I stuck doing a few if statements?
j
You could do something like that:
Copy code
val firstname: String? = "John"
    val middlename: String? = " "
    val lastname: String? = null
    
    val names: String = listOf(firstname, middlename, lastname)
    .filter { !it.isNullOrBlank() } 
    .joinToString(" ")
2
a
Copy code
.joinToString(" ") { it.trim() }
2
(Just in case - but hopefully (to be more defensive and consistent) the trim() happens earlier!)
j
Indeed trim is a good idea. I would move it before filtering listOf(...) .map { it.trim() } .filter { ... } .joinToString(" ")
j
If the filtering is done with
isNullOrBlank
the trim doesn't need to be first. It avoids having one more operation since the
map
can be merged with
joinToString
👍 1
On a second note, thinking of names like this is technically wrong, unless your audience is very limited: https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/
3
j
It avoids having one more operation since the
map
can be merged with
joinToString
indeed 💯
c
thanks. i knew about joinToString, but didn't think about just creating a temp list 😂 Thanks all
c
No need to instantiate a list before filtering:
Copy code
listOfNotNull(firstName, middleName, lastName)
    .joinToString(" ")
j
This doesn't filter out the empty/blank parts, though
c
Ah, I'm assuming they're
null
when missing.
j
In the original example, they aren't. But yeah it's probably generally better to design it that way. If it comes from a text field, a
.takeIf { it.isNotBlank() }
is a simple way of cleaning things up
👍 2
e
Copy code
.ifBlank { null }
j
Oh, TIL
c
FWIW, Ended up with
Copy code
listOf(first, middle, last)
    .mapNotNull { it.trim().ifBlank { null } }
    .joinToString(" ")
Also, I'm using
ifBlank
all the time now. nice convenience method
c
There's also
ifEmpty
for collections
K 1
j
You should rarely need it within your code base, by the way, it should only be useful for cleaning input at the surface of your code. Throughout the code base, the data should be assumed "clean".
👍 2