简体   繁体   English

Kotlin:由具有具体化类型参数的函数覆盖

[英]Kotlin: Override by a function with reified type parameter

I am trying to pass a generic object to an override method that implements methods from an interface .我正在尝试将generic object传递给实现来自interface方法的override方法。

Unfortunately, I am getting an error when attempting to implements this.不幸的是,我在尝试执行此操作时遇到错误。 The error is as follows:错误如下:

Override by a function with reified type parameter由具有具体化类型参数的函数覆盖

Heres is my code这是我的代码

class ServiceVolley : ServiceInterface {

    val TAG = ServiceVolley::class.java.simpleName
    val basePath = "http://192.168.68.104:3005/"

    override inline fun <reified T> post(
        resource: String,
        payload: JSONObject,
        crossinline onSuccess: (response: JSONObject?) -> Unit,
        crossinline onError: (statusCode: Int) -> Unit
    ) {
        val jsonObjReq = object : JsonObjectRequest(Method.POST, basePath + resource, payload,
            Response.Listener<JSONObject> { response ->
                Klaxon().parse<T>(response.toString())
                onSuccess(response)
            },
            Response.ErrorListener { error ->
                onError(error.networkResponse.statusCode)
            }) {
            @Throws(AuthFailureError::class)
            override fun getHeaders(): Map<String, String> {
                val headers = HashMap<String, String>()
                headers["Content-Type"] = "application/json"
                headers["withCredentials"] = "true"
                return headers
            }
        }

        BackendVolley.instance?.addToRequestQueue(jsonObjReq, TAG)
    }
}
interface ServiceInterface {
    fun <T> post(resource: String, payload: JSONObject, onSuccess: (response: JSONObject?) -> Unit, onError: (statusCode: Int) -> Unit)
}

and I call this function with the following我用以下命令调用这个函数

apiController.post<User>("user/sign-in", payload,
{ user: User? ->
    Log.d("RESPONSE", user.toString());
},
{ statusCode: Int ->
    Log.d("ERROR", statusCode.toString())
})

See this issue: Overridding by inline function should be a warning, overriding by a function with reified type parameter should be an error .请参阅此问题:由内联函数覆盖应该是警告,由具有具体化类型参数的函数覆盖应该是错误

Basically: with virtual functions, which function is called is determined at runtime;基本上:对于虚函数,调用哪个函数是在运行时确定的; so they can't be inlined because the compiler doesn't know which function to inline.所以它们不能被内联,因为编译器不知道要内联哪个函数。 When you do something like当你做类似的事情时

interface A {
    fun f(t: Int)
}

class AImpl : A {
    override inline fun f(t: Int) {
        println(t.toString())
    }
}

val a: A = AImpl()
a.f(1)

the non-inlined version of AImpl.f gets called. AImpl.f的非内联版本被调用。

But functions with reified must be inlined, or it won't work.但是带有reified函数必须内联,否则将无法工作。 So they can't be used to override.所以它们不能用于覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM