hisham bin awiad
10/17/2022, 8:40 AMprivate fun getCustomEmployeeShifts(
employeeShifts: List<Shifts>?,
approvedOvertimes: List<ApprovedOvertimesModel>?
): List<Shifts> {
val resultList = mutableListOf<Shifts>()
var sh: Shifts
employeeShifts?.forEach { shiftsModel ->
sh = shiftsModel
approvedOvertimes?.forEach { appOverModel ->
if (sh.id == appOverModel.employeeShiftId) {
sh.approvedOvertimes.add(appOverModel)
}
}
resultList.add(sh)
}
return resultList.toList()
}
Joffrey
10/17/2022, 8:41 AMShifts
and ApprovedOvertimeModel
)hisham bin awiad
10/17/2022, 8:43 AMJoffrey
10/17/2022, 8:44 AMJoffrey
10/17/2022, 8:53 AMvar
when unnecessary. Here just declare the sh
variable inside the forEach
and it can be a val
. In fact, once you do that, you may realize you already have that val (shiftsModel
) so you don't need sh
at all.
3. the resultList
serves no purpose, you modify the existing list in place and add all elements from it to the result, so since both lists are read-only, you are basically returning the same list. If you really want a defensive copy of that list, you can still return a list using toList()
- but do it on the original. That being said, returning another list usually implies that you didn't modify the original, so in the name of least surprise I would advise to not return anything at all, so people know you're actually mutating the parameters
Which would give the following:
data class Shifts(
val id: String,
val approvedOvertimes: MutableList<ApprovedOvertimesModel>,
)
data class ApprovedOvertimesModel(val employeeShiftId: String)
private fun getCustomEmployeeShifts(
employeeShifts: List<Shifts>,
approvedOvertimes: List<ApprovedOvertimesModel>
) {
employeeShifts.forEach { shiftsModel ->
approvedOvertimes.forEach { appOverModel ->
if (shiftsModel.id == appOverModel.employeeShiftId) {
shiftsModel.approvedOvertimes.add(appOverModel)
}
}
}
}
Javier
10/17/2022, 8:53 AMJavier
10/17/2022, 8:53 AMdata class Shifts(val id: Int, val approvedOvertimes: MutableList<ApprovedOvertimesModel>)
data class ApprovedOvertimesModel(val employeeShiftId: Int)
fun getCustomEmployeeShifts(
employeeShifts: List<Shifts>?,
approvedOvertimes: List<ApprovedOvertimesModel>?
): List<Shifts> {
val resultList = mutableListOf<Shifts>()
var sh: Shifts
employeeShifts?.forEach { shiftsModel ->
sh = shiftsModel
approvedOvertimes?.forEach { appOverModel ->
if (sh.id == appOverModel.employeeShiftId) {
sh.approvedOvertimes.add(appOverModel)
}
}
resultList.add(sh)
}
return resultList.toList()
}
Javier
10/17/2022, 8:54 AMmap
instead of forEach
. You can return a buildList { }
too.Joffrey
10/17/2022, 8:57 AMShifts
instances) rather than mutating existing instances, unless this code path is super performance-critical. It usually avoids a lot of bugs.Robert Williams
10/18/2022, 3:57 PMRobert Williams
10/18/2022, 4:01 PMval overtimesByShift = approvedOvertimes?.groupBy { it.employeeShiftId }
employeeShifts?.forEach { it.approvedOvertimes = overtimesByShift[it.id] }