Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a List in Kotlin based on Conditions

At the moment I have this fun:

private fun validateArguments(city: String, state: String, country: String, zip: String): List<String> {

        val list: MutableList<String> = mutableListOf()
        if (city.isNullOrBlank()) list.add("Invalid city")
        if (state.isNullOrBlank()) list.add("Invalid state")
        if (country.isNullOrBlank()) list.add("Invalid country")
        if (zip.isNullOrBlank()) list.add("Invalid zip code")

        return list.toList()
}

and I was wondering if there a more elegent way to create the list. The final list could also be a MutableList I guess.

like image 644
Bart Romano Avatar asked Feb 02 '26 17:02

Bart Romano


2 Answers

If you're using Kotlin 1.6+, there are builder APIs for lists, sets, and maps:

val list = buildList {
    if (city.isNullOrBlank()) add("Invalid city")
    if (state.isNullOrBlank()) add("Invalid state")
    if (country.isNullOrBlank()) add("Invalid country")
    if (zip.isNullOrBlank()) add("Invalid zip code")
}

This allows to limit the scope of the mutable handle to the list, and only expose the read-only interface. It also fits nicely in extracted methods.

like image 86
Joffrey Avatar answered Feb 05 '26 06:02

Joffrey


I'm not sure there's a single, obviously better way; it's already fairly concise and clear.

But here's one alternative, using the listOfNotNull and takeIf functions to avoid an explicit temporary list:

private fun validateArguments(city: String, state: String, country: String, zip: String)
    = listOfNotNull(
        "Invalid city".takeIf{ city.isNullOrBlank() },
        "Invalid state".takeIf{ state.isNullOrBlank() },
        "Invalid country".takeIf{ country.isNullOrBlank() },
        "Invalid zip code".takeIf{ zip.isNullOrBlank() })

Here takeIf() returns null if the condition isn't met; and listOfNotNull() then removes all those nulls, leaving only the errors for those which were met.

like image 29
gidds Avatar answered Feb 05 '26 06:02

gidds