What's the idiomatic way to map a nullable list? ...
# announcements
p
What's the idiomatic way to map a nullable list? Let's say I have this class
Copy code
class ProductModel {
   val productListModel: List<ProductListModel>? = null,
}
And I have the mapper like this
Copy code
fun map(input : ProductModel) : List<Product>{
  return input.productListModel?.map{Product(....)}.orEmpty()
}
Is there another elegant way? If the list is null or empty I should return an empty List of Product and if not, the list mapped
t
In your model, why would you allow a nullable list? The default can just be an
emptyList()
and avoid the whole issue
👆 4
r
If
productListModel
has to be nullable for some reason, then you can save yourself one character by doing
input.productListModel.orEmpty().map{Product(....)}
💯 2
j
@Rob Elliot but then even if the list is empty it will try to map, right?
r
Hmm - interesting, I’d assumed
List<T>.map
would have an
if empty return this
or perhaps an
if empty return emptyList()
, which always returns the same
object
, as an optimisation. But looks like it instantiates a new list instance regardless. Generally I prefer to get away from null as soon as possible, but perhaps in this case that’s bad advice.
👍 1
p
Yes, I did it like this because I thought that checking the null or empty it will avoid the
map