В Kotlin reduce - это функция расширения для коллекций, которая позволяет выполнить агрегирующую операцию над всеми элементами коллекции, последовательно применяя заданную функцию.
1. Базовый синтаксис
fun <S, T> Iterable<T>.reduce(
operation: (accumulator: S, nextElement: T) -> S
): S
2. Простой пример суммирования
val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.reduce { acc, number ->
acc + number
}
// Результат: 15 (1+2+3+4+5)
3. Механизм работы
// Пошаговое выполнение reduce
// [1, 2, 3, 4, 5]
// 1-й проход: acc = 1, number = 2 → acc = 3
// 2-й проход: acc = 3, number = 3 → acc = 6
// 3-й проход: acc = 6, number = 4 → acc = 10
// 4-й проход: acc = 10, number = 5 → acc = 15
4. Варианты использования
Умножение
val factorial = listOf(1, 2, 3, 4, 5).reduce { acc, number ->
acc * number
}
// Результат: 120
Конкатенация строк
val words = listOf("Kotlin", "is", "awesome")
val sentence = words.reduce { acc, word ->
"$acc $word"
}
// Результат: "Kotlin is awesome"
5. Отличия от fold
// reduce требует, чтобы коллекция была непустой
// fold позволяет начать с начального значения
// reduce
val numbers = listOf(1, 2, 3)
val sum = numbers.reduce { acc, number -> acc + number }
// fold
val sumWithInitial = numbers.fold(10) { acc, number ->
acc + number
}
// Результат: 16 (10 + 1 + 2 + 3)
6. Обработка ошибок
// Пустая коллекция вызовет исключение
val emptyList = emptyList<Int>()
val sum = emptyList.reduce { acc, number -> acc + number }
// UnsupportedOperationException
// Безопасная альтернатива - reduceOrNull
val safeSum = emptyList.reduceOrNull { acc, number -> acc + number }
// Вернет null для пустой коллекции
7. Продвинутый пример
data class Person(val name: String, val age: Int)
val people = listOf(
Person("Alice", 25),
Person("Bob", 30),
Person("Charlie", 35)
)
// Найти старейшину
val oldest = people.reduce { acc, person ->
if (acc.age > person.age) acc else person
}
// Результат: Person("Charlie", 35)
8. Особенности реализации
// Внутренняя реализация похожа на:
fun <S, T> Iterable<T>.reduce(
operation: (accumulator: S, nextElement: T) -> S
): S {
val iterator = iterator()
// Первый элемент как начальное значение
var accumulator = iterator.next() as S
// Применяем операцию ко всем остальным
while (iterator.hasNext()) {
val nextElement = iterator.next()
accumulator = operation(accumulator, nextElement)
}
return accumulator
}