在Volley的背景下,Kotlin“它”的语法
有人可以向我解释这段代码中的Kotlin'it'语法是如何工作的吗? 这段代码很难阅读,有人把它发给我来解决我的问题,它对于多个连续的请求像魔术一样工作。 我之前使用过Volley,但是这个代码很混乱。 我相信Kotlin比Java更容易阅读,但是这个特殊的代码很难理解。
val responses = mutableListOf<JSONObject>() val myAPIUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=" val myAPIKey = "REMOVED" val transportMode = listOf("&mode=driving", "&mode=walking", "&mode=bicycling", "&mode=transit&transit_mode=bus", "mode=transit&transit_mode=subway", "mode=transit&transit_mode=train") val queue = Volley.newRequestQueue(this) transportMode.map { "$myAPIUrl$locationCoordinatesLat,$locationCoordinatesLong&destinations=$locationInput$it&key=$myAPIKey" } .map { JsonObjectRequest(Request.Method.GET, it, null, Response.Listener { responses.add(it) }, Response.ErrorListener { //nothing }) }.forEach { queue.add(it) } }
首先, transportMode
列表中的每个条目映射到相同的字符串"$myAPIUrl$locationCoordinatesLat,$locationCoordinatesLong&destinations=$locationInput$it&key=$myAPIKey"
,基本上抛弃传输模式。 我们称之为A
然后,这些字符串的结果列表被映射到一个JsonObjectRequest
,在该对象中URL被设置为it
,它是列表的字符串A
之一。 每个JsonObjectRequest
也有成功回调和错误回调。 前者接收生成的JSONObject
作为隐式的参数,所以JSONObject
responses.add(it)
将JSONObject
添加到响应列表中。
最后it
可以在传递给forEach
的lambda函数中找到。 它是在最后一个map
step中创建的JsonObjectRequest
对象之一。 lambda将它添加到Volley请求队列中。
为了使事情更清楚,我已经用一些提示扩充了你的代码:
transportMode.map { mode -> "$myAPIUrl$locationCoordinatesLat,$locationCoordinatesLong&destinations=$locationInput$it&key=$myAPIKey" } .map { url -> JsonObjectRequest(Request.Method.GET, url, null, Response.Listener { responseJsonObject -> responses.add(responseJsonObject) }, Response.ErrorListener { //nothing }) }.forEach { request -> queue.add(request) }
it
是函数文字中使用的单个参数的隐式名称 。
例如,在您的代码中, transportMode
是一个Array<String>
,当您调用时:
transportMode.map { "..." }
在这里你传递一个函数,它有一个String
作为唯一的参数和一个String
作为返回值。 所以, it
里面的花括号代表一个String
。
如果你认为it
不适合你。 你可以明确地命名参数:
transportMode.map { tag -> "$myAPIUrl$locationCoordinatesLat,$locationCoordinatesLong&destinations=$locationInput$tag&key=$myAPIKey" }
it
是最接近的lambda的单个参数的隐式名称。
list.forEach { queue.add(it) } // it represents current item list.forEach { item -> queue.add(item) } // Rename it if you like // first it from nestList, second from the first it nestList.forEach { it.forEach { queue.add(it) } }
阅读更多的官方文件 。
it
变量是高阶函数和Lambdas中单个参数的隐式名称 。
在第一个map()
你创建了一个带有"...$it&key=$myAPIKey""
结尾的模式的URL,这里就像"&mode=driving"
。
用第二个map()
创建对urls( it
用作参数)的请求,并使用responses.add(it)
将侦听器中给予您的响应添加到响应列表中。
随着forEach()
你迭代所有的请求,并入队这些。