0
0
Kotlinprogramming~5 mins

Fold and reduce operations in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the fold function do in Kotlin?
The fold function starts with an initial value and combines it with elements of a collection one by one using a given operation, producing a single result.
Click to reveal answer
beginner
How is reduce different from fold in Kotlin?
reduce does not take an initial value; it uses the first element of the collection as the starting point and combines the rest. fold requires an explicit initial value.
Click to reveal answer
intermediate
What happens if you call reduce on an empty list in Kotlin?
Calling reduce on an empty list throws a NoSuchElementException because there is no first element to start the operation.
Click to reveal answer
beginner
Explain the role of the lambda function in fold and reduce.
The lambda function defines how to combine the current accumulated value with the next element. It takes two parameters: the accumulator and the current element, and returns the new accumulator.
Click to reveal answer
beginner
Give a simple example of using fold to sum a list of numbers starting from 10.
Example: <br>val numbers = listOf(1, 2, 3)<br>val sum = numbers.fold(10) { acc, num -> acc + num }<br>This results in sum = 16 because 10 + 1 + 2 + 3 = 16.
Click to reveal answer
What initial value does reduce use when combining elements?
ANull
BZero
CThe first element of the collection
DAn explicit initial value provided by the user
Which function requires an explicit initial value: fold or reduce?
Afold
Breduce
CBoth
DNeither
What exception is thrown if reduce is called on an empty list?
ANullPointerException
BIndexOutOfBoundsException
CIllegalArgumentException
DNoSuchElementException
In the lambda for fold, what do the two parameters represent?
AThe index and the element
BThe accumulator and the current element
CThe collection and the element
DThe previous element and the next element
What will be the result of listOf(2, 3, 4).fold(1) { acc, n -> acc * n }?
A24
B10
C9
D1
Describe how fold and reduce work in Kotlin and when you might use each.
Think about starting points and empty lists.
You got /4 concepts.
    Write a Kotlin example using reduce to find the maximum number in a list.
    Use maxOf or comparison inside lambda.
    You got /4 concepts.