android - Kotlin:如何将子数组减少为单个数组?
问题描述
我在 Swift 中有一段代码,可以将对象列表简化为pobjectsTVSchedule
数组。TVMatch
每个 TVSchedule 都有一个名为 events 的属性,即一个TVMatch
es 列表。
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 代码给了我一个类型错误,并且无法编译。这里有什么问题?
解决方案
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
请注意,您实际上可以完全简化使用flatMap
to (旁注:如果您使用这种方法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
或者,如果您确实需要matches
type ArrayList
,请flatMapTo
改用:
val matches = timeSlots.flatMapTo(ArrayList()) { it.events }
您当然可以保留get()
如果必须的话,或者只是将匹配项的获取移至其自己的功能,例如:
fun getMatches() = timeSlots.flatMapTo(ArrayList()) { it.events }
推荐阅读
- flutter - SliverList 上的粘性标题
- java - 在单元测试中使用 JPA 保存时没有结果
- c# - 当我单击 C# WinForms 中的按钮时,在哪里调用 InvokeOnClick() 方法?
- actions-on-google - 使用 Dialogflow 和 WebhookClient (v2 API) 保存 Google Actions 的会话数据
- keyboard - 美国布局的变音符号和其他符号的替代键盘映射
- c# - Powershell Topshelf Uninstall 继续锁定文件
- android - 在通过 POST 方法将图像发送到服务器之前调整图像大小
- javascript - 如何通过for循环将新数据添加到数组
- javascript - LinkedIn 与 LinkedIn 的 testDevCo 一起使用,而不是与想要的公司页面一起使用
- javascript - 无法访问对象的属性 - 对象