Víctor Martín
Víctor Martín

Reputation: 3450

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

Upvotes: 0

Views: 452

Answers (2)

cactustictacs
cactustictacs

Reputation: 19592

Here's what you're doing

data.addAll(recursiveResponse.body()?.data)

You're having to null-check (with ?) before accessing data, because body() can return null. If body() returns a value, the whole expression evaluates to data. If it returns null, the whole expression evaluates to null - and calling addAll with null is not allowed. So you can't pass in a nullable collection.

That means you need to null-check your results before you try to add them:

recursiveResponse.body()?.data?.let { results -> data.addAll(results) }

This null-checks everything down to data, and if nothing in the chain evaluates to null, then it calls the let block. Because the list being passed in has been null-checked, it definitely isn't null, so it's cast to the non-null type that addAll accepts. This is how you handle potentially null stuff safely - by ensuring that it isn't null before you try to use it.

Upvotes: 2

Mohammad Derakhshan
Mohammad Derakhshan

Reputation: 1572

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!!

Upvotes: 1

Related Questions