tehnolog
tehnolog

Reputation: 1214

How to work with foldRight() in Kotlin?

I try this code

        println(listOf(1, 2, 4).foldRight(0) { total, next ->
            total - next
        })

I thought it works like 0 + 4 - 2 - 1 = 1. But it returns 3. Why? Sorry for this silly question.

Upvotes: 3

Views: 4284

Answers (1)

gpeche
gpeche

Reputation: 22514

foldRight works by accumulating the result from right to left. In your case, it is going to do

(1 - (2 - (4 - 0))) = (1 - (2 - 4)) = 1 - (-2) = 3

Note that your operation has its parameters in the wrong order, foldRight will pass you the next element as the first parameter and the accumulator as the second parameter. See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/fold-right.html. If you swap them, you would have

(((0 - 4) - 2) - 1) = - 7

unless I am getting something wrong

Upvotes: 14

Related Questions