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?✗ Incorrect
reduce uses the first element of the collection as the starting point.Which function requires an explicit initial value:
fold or reduce?✗ Incorrect
fold requires an initial value; reduce does not.What exception is thrown if
reduce is called on an empty list?✗ Incorrect
Calling
reduce on an empty list throws NoSuchElementException.In the lambda for
fold, what do the two parameters represent?✗ Incorrect
The lambda takes the accumulator (current result) and the current element to produce a new accumulator.
What will be the result of
listOf(2, 3, 4).fold(1) { acc, n -> acc * n }?✗ Incorrect
The calculation is 1 * 2 * 3 * 4 = 24.
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.