🐦 Kotlin
Intermediate
What is the fold function in Kotlin?
Answer
fold accumulates a value starting from an initial value and applying an operation to each element from left to right. val sum = numbers.fold(0) { acc, n -> acc + n }. The accumulator (acc) starts at the initial value and is updated by each element. Unlike reduce, fold always has an explicit initial value, so it is safe for empty collections. Use foldRight to process elements from right to left. Fold is very powerful for building complex results like grouped maps or custom data structures from a collection.