How to put lambda expression after parameters on mapTo to call legal syntax?

I found a piece of code that I do not understand.

I will convert a JSONArrayto List.
Kotlin provides a function mapToin it stdlib( link )

MAPTO

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

Applies this transform function to each item in the source collection and adds the results to the specified destination.

These functions have 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 a valid syntax (not expected):

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

As you can see, the function parameters end after outputListand the lambda expression is simply placed 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 it is not (???):

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

:

, - , , :

lock (lock) {
    sharedResource.operation()
}

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
}

:

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

, , lambda - .

, -, .

+6

Source: https://habr.com/ru/post/1016164/


All Articles