首页 > 解决方案 > Kotlin:如何将子数组减少为单个数组?

问题描述

我在 Swift 中有一段代码,可以将对象列表简化为pobjectsTVSchedule数组。TVMatch每个 TVSchedule 都有一个名为 events 的属性,即一个TVMatches 列表。

swift中的代码如下:

var matches: [TVMatch] {
    let slots = timeSlots.reduce(into: [TVMatch]()) { (result, schedule) in
        result.append(contentsOf: schedule.events)
    }
    return slots
}

我正在尝试在 Kotlin 中做同样的减少,我拥有的代码如下:

val matches: ArrayList<TVMatch>
    get() {
        val slots = timeSlots.fold(arrayListOf<TVMatch>()) { result, schedule ->
            result.addAll(schedule.events)
        }
        return slots
    }

但是,Kotlin 代码给了我一个类型错误,并且无法编译。这里有什么问题?

标签: androidkotlin

解决方案


addAll返回 a boolean,但 - 操作的返回值fold应该与给定的初始对象具有相同的类型(在这种情况下ArrayList)。result您只需在您的addAll-statement之后添加即可轻松解决该问题,例如:

result.addAll(schedule.events)
result // this is now the actual return value of the fold-operation

或者只是使用apply或类似的代替:

result.apply {
  addAll(schedule.events)
} // result is the return value then

请注意,您实际上可以完全简化使用flatMapto (旁注:如果您使用这种方法matches,当然只评估一次,但flatMap无论如何这里是明星;-))):

val matches = timeSlots.flatMap { it.events } // this is a new list! (note, if you do several mappings in a row, you may want to use timeSlots.asSequence().flatMap { }.map { }.toList() / or .toMutableList() instead

或者,如果您确实需要matchestype ArrayList,请flatMapTo改用:

val matches = timeSlots.flatMapTo(ArrayList()) { it.events }

您当然可以保留get()如果必须的话,或者只是将匹配项的获取移至其自己的功能,例如:

fun getMatches() = timeSlots.flatMapTo(ArrayList()) { it.events }

推荐阅读