我发现了一段我看不懂的代码。
我正在将 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/