list - <kotlin>
list
for (music in list.listIterator())
和
for (i in list.indices)
和
for (i in list)
listIterator()
这是“可变迭代器”,用于边遍历边修改列表(如添加/删除元素)
val iterator = lsit.listIterator()
while (iterator.hasNext()) {
val music = iterator.next()
if (music.id == 123) {
iterator.remove() // ✅ 安全删除
}
}
🧠 关键特性:
-
可以调用
iterator.remove()或iterator.add()。 -
在遍历过程中修改集合,不会抛出
ConcurrentModificationException。
相比之下,如果你写成:
for (music in list) {
if (music.id == 123) {
list.remove(music) // ❌ 可能崩溃
}
}
这种是直接在列表上删除,会抛异常。
for (i in list.indices)
✅ 这是用索引访问元素,适合只读遍历或基于索引处理:
for (i in list.indices) {
val music = list[i]
println(music.title)
}
fold
Kotlin 的 fold 是一个强大又常用的扩展函数,用于在集合中累加计算(reduce with an initial value),从一个初始值开始遍历集合,并逐步应用一个操作函数,最终生成一个值。
✅ 基本语法
fun <T, R> Iterable<T>.fold(
initial: R,
operation: (acc: R, T) -> R
): R
-
initial:初始值(累加器的起始状态)。 -
operation:接收当前累加值和当前元素,返回新的累加值。 -
最终返回一个值,类型为
R。
源码:
public inline fun <T, R> Iterable<T>.fold(initial: R, operation: (acc: R, T) -> R): R {
var accumulator = initial
for (element in this) accumulator = operation(accumulator, element)
return accumulator
}
for (element in this) accumulator = operation(accumulator, element) 可能有人对这个语法好奇,其实就是下面这段代码的简写形式:
for (element in this) {
accumulator = operation(accumulator, element)
}
✅ Kotlin 支持单行语句块省略花括号
这不是一个特殊的“语法糖”,而是 Kotlin 语法的基本规则之一:
如果
for(或if/while等)控制结构后面只跟 一条语句,就可以省略{}花括号。
foldIndexed
foldIndexed 是 Kotlin 标准库提供的一个非常实用的扩展函数,它是 fold 的增强版,在迭代时同时提供元素索引(index)和值(element),用于从集合中“聚合”成一个最终值。
✅ 基本语法
fun <T, R> List<T>.foldIndexed(
initial: R,
operation: (index: Int, acc: R, element: T) -> R
): R
-
initial: 初始的累计值。 -
operation: 带有index的操作函数,参数是:-
index: 当前元素索引 -
acc: 当前累计值 -
element: 当前元素
-
-
返回值是最后累计的结果。
reduce
reduce 是 Kotlin 中集合操作的一个常用函数,用于将集合中的元素通过某种逻辑“归约”成一个值。它是典型的聚合函数。
public inline fun <S, T : S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S {
val iterator = this.iterator()
if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
var accumulator: S = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(accumulator, iterator.next())
}
r
✅ 简单定义:
kotlin
复制编辑
fun <S, T : S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S
-
第一个元素作为初始
acc值 -
然后依次把每个元素合并进
acc,得到最终结果
✅ 示例
val nums = listOf(1, 2, 3, 4, 5)
val sum = nums.reduce { acc, e -> acc + e }
println(sum) // 输出:15
🆚 和 fold 的区别?
| 特性 | reduce | fold |
|---|---|---|
| 初始值 | 使用集合第一个元素 | 你自己指定初始值 |
| 适用于空集合? | ❌ 报错 | ✅ 可执行,返回初始值 |
| 返回值类型 | 与元素同类型 | 可以不同类型 |
| 更安全的版本 | reduceOrNull() | fold() 本身安全 |
更多推荐
所有评论(0)