lambda - 如何将 lambda 表达式放在 mapTo 调用合法语法的参数之后?

标签 lambda kotlin

我发现了一段我看不懂的代码。

我正在将 JSONArray 转换为 List
Kotlin 在其 stdlib( link )

中提供了函数 mapTo

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.

这个函数有2个参数,可以这样使用(如预期的那样):

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

但显然这也是有效的语法(不是预期的):

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

如您所见,函数参数在 outputList 之后结束,而 lambda 表达式只是放在函数调用的末尾。


此外,这是合法的(如预期的那样):

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

但这不是(???):

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.

文档明确指出,要使上述方法起作用,最后一个参数必须是 lambda 表达式,而不是匹配类型的变量。

关于lambda - 如何将 lambda 表达式放在 mapTo 调用合法语法的参数之后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43113430/

相关文章:

python - lambda 函数不关闭 Python 中的参数?

amazon-web-services - 使用 API 网关和无服务器框架在 AWS Lambda 上超过了速率

list - 对每个列表元素应用谓词

c# - 在 C# 中,Lambda 表达式是对象吗?

android - Kotlin:如何访问另一个类的字段?

Kotlin 惰性切片数组

kotlin - Jacoco不生成xml文件

c++ - 制作一个单一的捕获 Lambda

arrays - Kotlin:泛型数组的泛型集合

android - 使用 Dagger Android 处理器的 kapt 构建失败