jeudi 20 décembre 2018

Elegant way to add elements in collections in Kotlin

I have a repeating pattern in my code in Kotlin where I have to check if the items are not null and add them to a collection and then return it. I have found Kotlin function listOfNotNull, but I will not work if I want to add a collection to the collection (replace addAll()). Do you know a non-verbose way to add elements to collection?

Example of the code I want to simplify:

private fun getItems(): List<BaseItem> {
    val items = ArrayList<BaseItem>()

    componentA?.let { items.add(it) }

    componentB?.let {
        items.add(it)
    }

    additionalComponents?.let {
        items.addAll(it)
    }

    componentD?.let { items.addAll(it) }

    return items
}

Aucun commentaire:

Enregistrer un commentaire