Kotlin 语法混乱:使用 lambda 传递接口

Kotlin syntax confusion: passing an interface with a lambda

我正在为 Android 学习 Kotlin 编程,我正在努力深入理解这段代码(有效)。 来自网络请求的Volley库:

//Network stuff
    // Request a string response from the provided URL.
    val jsonObjectRequest = object : JsonObjectRequest(Method.POST, http, ob,
            Response.Listener<JSONObject> { response ->
                // Display the first 500 characters of the response string.
                Log.d("Debug","Response is: ${response.toString()} ")

            },
            Response.ErrorListener { error ->
                Log.d("Debug","That didn't work! Code: ${error.message}")
            })
    {
        @Throws(AuthFailureError::class)
            override fun getHeaders(): Map<String, String> {
                val headers = HashMap<String, String>()
                headers.put("Content-Type", "application/json")
                headers.put("Accept", "application/json")
                return headers
        }

    }

我的问题是关于第一个块,就在 JsonObjectRequest 对象的构造函数内部。我知道对象构造、lambdas、类 和接口,但有一件小事我没弄明白。而且,我已经看过这个帖子 .

我的问题是:用于构造 JsonObjectRequest 的第四个参数发生了什么?据我所知,有一个 lambda 覆盖了一些与 Response.Listener<JSONObject> 相关的函数,但我没有找到任何对此语法的引用。

总而言之,objectRequest 具有前一个构造函数:

    public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
        Listener<JSONObject> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
}

听众有以下部分:

public class Response<T> {

/** Callback interface for delivering parsed responses. */
public interface Listener<T> {
    /** Called when a response is received. */
    void onResponse(T response);
}

/** Callback interface for delivering error responses. */
public interface ErrorListener {
    /**
     * Callback method that an error has been occurred with the
     * provided error code and optional user-readable message.
     */
    void onErrorResponse(VolleyError error);
}

读到这里,我明白了我们使用这种语法实现了 Listener 接口,但我不明白为什么我们使用 lambda,因为在 Listener 中没有对它的引用,特别是这是什么意思:

 Response.Listener<JSONObject> { response ->
            // Display the first 500 characters of the response string.
            Log.d("Debug","Response is: ${response.toString()} ")

        }

有人愿意对此进行解释或指出与此语法相关的一些参考资料吗?

这是一个SAM-conversion。因为 Response.Listener<JSONObject> 是一个 SAM 接口(只有一个方法,没有 default 实现)并且在 Java 中定义,你可以写

Response.Listener<JSONObject> /* lambda */

lambda 用作方法的实现。 IE。相当于

object : Response.Listener<JSONObject> {
    override fun onResponse(response: JSONObject) {
        Log.d("Debug","Response is: ${response.toString()} ")
    }
}