CrazySynthax
CrazySynthax

Reputation: 15048

Kotlin: how can 'fold' function take one argument?

According to the documentation of Kotlin, the function "fold" takes two arguments: an initial value and an operation. However, I see that the following code compiles and works well:

listOf<Int>(1, 2, 3).fold(0) { x, y -> x + y }

There is only one argument inside the parenthesis, instead of two. If so, how is it possible that the code's compilation succeeds? it should be an error.

Upvotes: 0

Views: 190

Answers (1)

H&#233;ctor
H&#233;ctor

Reputation: 26084

According docs:

In Kotlin, there is a convention: if the last parameter of a function is a function, then a lambda expression passed as the corresponding argument can be placed outside the parentheses.

and

If the lambda is the only argument to that call, the parentheses can be omitted entirely.

This feature, called trailing lambda, makes the code hard to understand for novice Kotlin developers, but when you get it, it allows writting DSL-like code, like this:

val person = person {
    name = "John"
    age = 25
    address {
        street = "Main Street"
        number = 42
        city = "London"
    }
}

And that's why it is such a powerful language feature.

Upvotes: 3

Related Questions