How is putting the lambda expression after the par

2020-03-08 09:22发布

问题:

I found a piece of code I do not understand.

I am transforming a JSONArray into a List.
Kotlin provides the function mapTo in it's stdlib(link)

mapTo

inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(
    destination: C, 
    transform: (T) -> R
): C (source)

Applies the given transform function to each element of the original collection and appends the results to the given destination.

This functions has 2 parameters and can be used like this (as expected):

(0..jsonArray.length() - 1).mapTo(targetList, {it -> jsonArray[it].toString()})

But apparently this is also valid syntax (not expected):

(0..jsonArray.length()-1).mapTo(targetList) {it -> jsonArray[it].toString()}

As you can see, the function parameters end after outputList and the lambda expression is just put at the end of the function call.


Furthermore this is legal (as expected):

val transformation = {it : Int -> jsonArray[it].toString()}
(0..jsonArray.length()-1).mapTo(targetList, transformation)

but this is not (???):

val transformation = {it : Int -> jsonArray[it].toString()}
(0..jsonArray.length()-1).mapTo(targetList) transformation

回答1:

As stated in the documentation:

In Kotlin, there is a convention that if the last parameter to a function is a function, and you're passing a lambda expression as the corresponding argument, you can specify it outside of parentheses:

lock (lock) {
    sharedResource.operation()
}

Another example of a higher-order function would be map():

fun <T, R> List<T>.map(transform: (T) -> R): List<R> {
    val result = arrayListOf<R>()
    for (item in this)
        result.add(transform(item))
    return result
}

This function can be called as follows:

val doubled = ints.map { it -> it * 2 }

Note that the parentheses in a call can be omitted entirely if the lambda is the only argument to that call.

The documentation states clearly that for the above to work the last argument must be lambda expression and not a variable of matching type.



标签: lambda kotlin