kotlincollectionsnullable

Combining multiple nullable collection in Kotlin


I am working on a kotlin function that needs to combine a series of nullable collections into a single output collection. The obvious solution is brute force. Use a series of if/else statements to figure out which collections are not null and combine them accordingly. However, this solution is messy and error prone. What I'm looking for is an existing kotlin function that can take n+1 nullable collections and output a new collection with their combined contents. Does something like this exist, or do I simply have to do this the hard way?

Example:

//list1:['a','b','c']
//list2:null
//list3:['x','y']
func combineStuff(list1:List<String>?, list2:List<String>?, list3:List<String>? )
{
    return list1 + list2 + list3
    //['a','b','c','x','y']
}

Solution

  • The simplest option may be to use the .orEmpty() method available on all Collection<T>? values:

    list1.orEmpty() + list2.orEmpty() + list3.orEmpty()
    

    list.orEmpty() return the list itself, if it's non-null. Otherwise, it returns an empty list. In other words, using it is equivalent to (list ?: emptyList()).

    See also the official API documentation