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

推荐答案

如第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.

Kotlin相关问答推荐

Kotlin中函数引用的否定

Kotlin 说不需要强制转换,但删除后会出现新警告

如何获取@JsonProperty 名称列表?

按钮无法在 Android Studio 上打开新活动

Kotlin 协程按顺序执行,但仅在生产机器上执行

Kotlin - 协程未按预期执行

如何将glide显示的图像下载到设备存储中.Kotlin

Kotlin 可打包类抛出 ClassNotFoundException

Kotlin - 创建指定长度的随机整数的 ArrayList?

类型是什么意

Kotlin 和 Java 字符串拆分与正则表达式的区别

将 Kotlin 类属性设置器作为函数引用

Kotlin 中 lambda 表达式中的默认参数

在 Koin 中提供一个 Instance 作为其接口

主机名不能为空

Kotlin 中的内联构造函数是什么?

Kotlin - computed var 属性的用处?

内联 onFocusChange kotlin

Android studio 4.0 新更新版本说 Kotlin 与这个新版本不兼容

你如何在 Kotlin 中注释 Pair 参数?