I have a data class like ```data class ProfileItem...
# getting-started
v
I have a data class like
Copy code
data class ProfileItem(val id: String, val item: Item)
data class Item (val code: String)
When I get a
List<ProfileItem>
from the 3rd service (can’t control it), the
item
field for some elements in the list might be
null
. And when I do
Copy code
val eligibleCodes = service.gerProfileItems().filter { it.item.code in approvedCodes }
it fails with NPE, so I had to do
filter { it.item != null }
once I got the list. And IntelliJ complains about this filtering saying that this condition is always true. Is it an issue with the IntelliJ IDEA’s inspection? Or I should do this operation differently?
j
The item value should be optional
Item?
in your class if
null
is an expected value for the field. Idea is right to complain that your code is not saying it is nullable.
👍 2
👍🏻 1
v
Got it, updated. Thanks @Jakub
🚀 1
t
alternatively you could set up the serialization you use in the API calls to automatically convert nulls to empty lists if that's what you desire. Anyways, your application should always expect the same format that is actually provided. You shouldn't expect non-null values if null is expected, just like @Jakub pointed out.
👍 3
s
and the way to remove nulls from a list is via `filterNotNull`:
Copy code
val itemsOrNulls: List<ProfileItem?> = service.gerProfileItems()
val items: List<ProfileItem> = itemsOrNulls.filterNotNull()