Home > Back-end >  Filter and Count Items in List inside a For Loop | Kotlin
Filter and Count Items in List inside a For Loop | Kotlin

Time:09-21

Hey guys I switched from Swift to Kotlin a few days ago and I'm trying to implement a similar function I have in swift into kotlin and failing

Here is what I'm doing in swift

  private var issues: [PathPmCore.Issue] = [] {
        didSet {
            AppState.shared.issues = issues
            taskModels.removeAll()
            var models = [ListModel]()
            var components = [Double]()
            
            for status in TaskState.allCases {
                let count = issues.filter({ isssue in
                    status.ids.contains(where: { statusId in
                        statusId == isssue.status.currentStatus.id
                    })
                }).count
                
                models.append(.init(activeTasks: .constant(count), circleState: .constant(status)))
                components.append(Double(count))
            }
            
            DispatchQueue.main.async {
                self.taskModels = models
                self.chartComponents = components
            }
        }

The way I approached it in Kotlin is similar

private var issues: List<Issues> = emptyList()
           set(value: List<Issues>){
               for (status in TaskState.values()) {
                   val models: ArrayList<ListModel> = arrayListOf<ListModel>()
                   val components = listOf<Double>()
                   val count = issues.filterNotNull().forEach { issue ->
                      status.ids.find {  statusId ->
                          statusId == issue.status.currentStatus.id
                      }
                   }
                    println(count)
                    value.count()
               }
           }

It works, with no errors but the one setter in Kotlin returns an empty array/list.

CodePudding user response:

Why it's empty

It's empty because you are not setting the backing field !

Possible Solution (maybe)

So, if I understood right what you are trying to achieve, here is a possible solution for your problema

    private var issues: List<Issues> = emptyList()
        set(value: List<Issues>){
            field = TaskState.values().map {
                 issues.filterNotNull().filter { issue ->
                    it.ids.any {  statusId ->
                        statusId == issue.status.currentStatus.id
                    }
                }
            }.flatten()
        }

I removed models and components because you are not using them.

  • Related