https://kotlinlang.org logo
#getting-started
Title
# getting-started
v

Vitali Plagov

10/18/2021, 8:24 AM
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

Jakub

10/18/2021, 8:34 AM
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

Vitali Plagov

10/18/2021, 8:39 AM
Got it, updated. Thanks @Jakub
🚀 1
t

Tobias Berger

10/18/2021, 9:24 AM
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

Stephan Schroeder

10/19/2021, 6:41 AM
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()
2 Views