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)
将给定的转换函数应用于原始集合的每个元素,并将结果附加到给定的目标.
此函数有2个参数,可以这样使用(如预期):
(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()}
如您所见,函数参数在outputList
之后结束,lambda表达式放在函数调用的末尾.
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