Android Kotlin:如何将子数组缩减为单个数组?
我在Swift中有一段代码,它将TVSchedule对象列表缩减为TVMatch对象数组。每个TVSchedule都有一个名为events的属性,即TVMatches的列表 swift中的代码如下所示:Android Kotlin:如何将子数组缩减为单个数组?,android,kotlin,Android,Kotlin,我在Swift中有一段代码,它将TVSchedule对象列表缩减为TVMatch对象数组。每个TVSchedule都有一个名为events的属性,即TVMatches的列表 swift中的代码如下所示: var matches: [TVMatch] { let slots = timeSlots.reduce(into: [TVMatch]()) { (result, schedule) in result.append(contentsOf: schedule.even
var matches: [TVMatch] {
let slots = timeSlots.reduce(into: [TVMatch]()) { (result, schedule) in
result.append(contentsOf: schedule.events)
}
return slots
}
val matches: ArrayList<TVMatch>
get() {
val slots = timeSlots.fold(arrayListOf<TVMatch>()) { result, schedule ->
result.addAll(schedule.events)
}
return slots
}
我正试图在Kotlin中执行相同的reduce,我的代码如下:
var matches: [TVMatch] {
let slots = timeSlots.reduce(into: [TVMatch]()) { (result, schedule) in
result.append(contentsOf: schedule.events)
}
return slots
}
val matches: ArrayList<TVMatch>
get() {
val slots = timeSlots.fold(arrayListOf<TVMatch>()) { result, schedule ->
result.addAll(schedule.events)
}
return slots
}
但是,Kotlin代码给了我一个类型错误,并且没有编译。这里有什么问题?addAll返回一个布尔值,但是-操作的返回值应该与本例中给定的初始对象ArrayList的类型相同。
只需在addAll语句后添加结果即可轻松解决该问题,例如:
result.addAll(schedule.events)
result // this is now the actual return value of the fold-operation
或者,只使用或类似:
result.apply {
addAll(schedule.events)
} // result is the return value then
请注意,您实际上可以将使用简化为旁注:如果您使用这种方法,那么匹配当然只会计算一次,但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
或者,如果确实要求匹配项的类型为ArrayList,请改用:
如果必须,您当然可以保留get,或者只是将获取匹配项移动到其自身的功能,例如:
fun getMatches() = timeSlots.flatMapTo(ArrayList()) { it.events }
addAll返回一个布尔值,但是-操作的返回值应该与本例中给定的初始对象ArrayList的类型相同。
只需在addAll语句后添加结果即可轻松解决该问题,例如:
result.addAll(schedule.events)
result // this is now the actual return value of the fold-operation
或者,只使用或类似:
result.apply {
addAll(schedule.events)
} // result is the return value then
请注意,您实际上可以将使用简化为旁注:如果您使用这种方法,那么匹配当然只会计算一次,但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
或者,如果确实要求匹配项的类型为ArrayList,请改用:
如果必须,您当然可以保留get,或者只是将获取匹配项移动到其自身的功能,例如:
fun getMatches() = timeSlots.flatMapTo(ArrayList()) { it.events }
我疯了吗,还是你不能用
val matches: List<TVMatch>
get() = timeSlots.flatMap { schedule -> schedule.events }
?我疯了吗,还是你不能用
val matches: List<TVMatch>
get() = timeSlots.flatMap { schedule -> schedule.events }
非常感谢你。有了你的详细解释,这是有道理的!我最后用的是平面地图。我得再深入一点功能性的东西不客气。。。您可能已经做到了:在更复杂的场景中,reduce/fold将派上用场。。。现在,对于您的特定场景,flatMap就足够了……非常感谢。有了你的详细解释,这是有道理的!我最后用的是平面地图。我得再深入一点功能性的东西不客气。。。您可能已经做到了:在更复杂的场景中,reduce/fold将派上用场。。。现在,对于您的特定场景,平面图就足够了……您是正确的,不是疯狂的,我非常感谢您!我已经接受了罗兰的回答,因为它更详细。你是正确的,没有疯,我非常感谢你!我接受了罗兰的回答,因为它更详细。