Search code examples
androidcollectionstype-conversionmutablelist

How to convert a mutablelist to a collection to use addAll?


I'm trying to retrieve some data from a service, and I'm working with a mutablelist to store the objects. The problem is that I need to add the retrived data to this mutablelist, but addAll says me that the type is mismatched.

screenshot


Solution

  • the problem here is nullability. you are passing a nullable collection( your MutableList) to a not-nullable collection. one approach is to mark the MutableList as not-nullable by adding !! at the end of your nullable Mutablelist. to give you some idea, check this snippet code:

        var collection:Collection<String> = emptyList()
        var myList:MutableList<String>? = mutableListOf()
        
        collection = myList!!