Home > Back-end >  Kotlin: Show non-null values with separator
Kotlin: Show non-null values with separator

Time:11-01

I want to show non-null values for my description, but for some reason native function is bugging out and I dont understand why.

Code:

val formattedDesc = listOfNotNull(boardingZone, accessPoint, duration, description).joinToString { " • " }

This should show string like this: "120 • A3 • 30 minutes • Ticket"

If some of those strings are null it should not be there.

But this function is returning this value: "•, •"

CodePudding user response:

By calling .joinToString { " • " } you are passing { " * "} as the final, functional parameter and all the other parameters the their defaults. So looking at the signature of joinToString it is:

public fun <T> Iterable<T>.joinToString(separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null)

so separator, prefix, postfix, limit and truncated are all the defaults and transform is { " • " } which runs on each element of your non-null list. So any non-null values are replaced with " • " whuch us the output you are seeing.

I guess you actually want:

listOfNotNull(boardingZone, accessPoint, duration, description).joinToString(" • ")

or even better use:

listOfNotNull(boardingZone, accessPoint, duration, description).joinToString(separator = " • ")

so that both you and readers of your code are sure what parameter is being passed.

  • Related