DEV Community


Discussion on: From Java to Kotlin in 20 minutes ⚡️

jmfayard profile image
Jean-Michel Fayard 🇫🇷🇩🇪🇬🇧🇪🇸🇨🇴 Author • Edited

Thanks a lot for your comment, this article was fun to write but I had no idea if it would be useful.
Fold() can be used for example to reimplement the sum of elements in a list. You give it an initial value (0), and a function that you apply to an accumulator (your sum so far) and each next element

fun main() {
    val ints = listOf(1, 4, 6, 8, 13)
    val sum = ints.fold(0) { sum, elem -> sum + elem }
    println(sum) // 32
Enter fullscreen mode Exit fullscreen mode


Before we treated what happened if you had 0, 1 or more than 1 element. Instead we could handle the case with 0 elements or more than 0. Next step was to use fold().

abhinav1217 profile image
Abhinav Kulshreshtha

Ok, So isEmpty check is replaced by having an initial value as parameter of fold. case for 1 or more is handled by lambda. I think I understand it now. So those check-steps are not needed anymore.

acc will be initialized as empty setOf string because that is what is passed inside fold(), c will be current iterated value. and then you call combineSolutions with acc and mapPin of c.

Man lambdas are trippy.

Thread Thread
jmfayard profile image
Jean-Michel Fayard 🇫🇷🇩🇪🇬🇧🇪🇸🇨🇴 Author

Exactly 👏🏻