Search code examples
androidkotlinstringbuilder

Build a String based on an Object with null values


I have my custom Object "Obersvation". This object has some values that could be null. Now I want to create a String based on those values, ignoring the null ones.

Right now I am doing something like this:

val myList = arrayListOf<String>()

if (observation.country != null) myList.add(observation.country)
if (observation.group != null) myList.add(observation.group)
if (observation.locality != null) myList.add(observation.locality)

val myString = TextUtils.join(" - ", myList)

This way, I check which values are null and only if they are not null I add it to my list. Then I proceed to separate all values with a dash. It is producing what I want, but I am afraid that doing like this is bad for performance since I am doing a lot of "ifs" in my code.

Any way to improve this?


Solution

  • listOfNotNull(observation.country, observation.group, observation.locality)
                 .joinToString(" - ")
    

    which may be simplifiable to:

    val myString = with(observation) {
      listOfNotNull(country, group, locality).joinToString(" - ")
    }
    

    It's probably the easiest to just use listOfNotNull and joinToString for this.