I found a piece of code that I do not understand.
I will convert a JSONArray
to List
.
Kotlin provides a function mapTo
in 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 outputList
and 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