• +91 9723535972
  • info@interviewmaterial.com

Kotlin Interview Questions and Answers

Question - What is the basic difference between the fold and reduce in Kotlin? Also, specify when to use which?

Answer -

Difference between the fold and reduce in Kotlin:

Fold: The fold takes an initial value and the first invocation of the lambda you pass to it. It will receive that initial value and the first element of the collection as parameters.

listOf(1, 2, 3).fold(0) { sum, element -> sum + element }  
The first call to the lambda will be with parameters 0 and 1. The ability to pass in an initial value is useful if you have to provide a default value or parameter for your operation.

Reduce: The "reduce" doesn't take an initial value. Instead, it starts with the first element of the collection as the accumulator.

listOf(1, 2, 3).reduce { sum, element -> sum + element }  
In the above example, it is denoted by sum. The first call to the lambda here will be with parameters 1 and 2.

Comment(S)

Show all Coment

Leave a Comment




NCERT Solutions

 

Share your email for latest updates

Name:
Email:

Our partners