althaf
10/01/2022, 10:38 AMdata class WishesByCategory(val id: Int, val name: String, val wishes: List<Wish>)
Code below is the from a repository mapper, that maps WishesResponse to the domain model, I'm stuck with the code at 'When' statement, since all the domains models are immutable in my case, i have to make it mutable list explicitly as shown below, however, the follow code doesn't work as each time the loop run it creates fresh list. Final result is that each domain model end up with empty list. Is there a better way to write this code ?
private fun List<WishesRpse>.toWishesByCategory(): List<WishesByCategory> {
val result: ArrayList<WishesByCategory> = ArrayList()
val expWbyC =
WishesByCategory(1, context.getString(R.string.jp_wish_cat_experience), listOf())
val eventWbyC =
WishesByCategory(2, context.getString(R.string.jp_wish_cat_events), listOf())
val serviceWbyC =
WishesByCategory(3, context.getString(R.string.jp_wish_cat_services), listOf())
val moblityWbyC =
WishesByCategory(4, context.getString(R.string.jp_wish_cat_mobility), listOf())
val othersWbyC =
WishesByCategory(5, context.getString(R.string.jp_wish_cat_others), listOf())
forEach {
when (it.id) {
in experience ->
expWbyC.wishes.toMutableList()
in events ->
eventWbyC.wishes.toMutableList()
in service ->
serviceWbyC.wishes.toMutableList()
in mobility ->
moblityWbyC.wishes.toMutableList()
else -> othersWbyC.wishes.toMutableList()
}.add(Wish(it.id, it.name))
}
listOf<WishesByCategory>(
expWbyC,
eventWbyC,
serviceWbyC,
moblityWbyC,
othersWbyC
).forEach {
if (it.wishes.isNotEmpty()) result.add(it)
}
return result
}
mattinger
10/02/2022, 3:21 AMpublic fun <T> Collection<T>.toMutableList(): MutableList<T> {
return ArrayList(this)
}
If you want to mutate the existing list in place, you'll have to cast it or pass in a list type that's already mutable (like ArrayList)
What you are doing here is creating a new list on each pass through the forEach loop, adding a value to that list and throwing it away.mattinger
10/02/2022, 3:21 AMenum class Category(val value: Int, val stringResId: Int) {
Experience(1, R.string.jp_wish_cat_experience),
...
}
fun category(wish: Wish): Category = ...
fun toWish(rpse: WishesRpse): Wish = ....
then you can use collection chaining operators to firsttransform the values into your domain model and then group by category. And then finally convert to WishesByCategory.
val wishesByCategory: Map<Category, List<Wish>> =
this.map { toWish(it) }
.groupBy { category(it) }
val wishesByCategoryList: List<WishesByCategory> = Category.values().map {
WishesByCategory(it.value, context.getString(it.stringResId), wishesByCategory.get(it) ?: listOf())
}
Mucking around with mutable lists is painful, and i recommend trying to take advantage of these kinds of operators provided to you by the kotlin stdlib