简体   繁体   中英

Need to use this method (Kotlin) in a Java Class

Im strugling with this. I have this Class in Kotlin with this Methods declared and i need to use that "onSuccess" inside a Java class and i dont know how to do it.

Kotlin class:

open class Callback<T>(val app: NetworkApplication) : retrofit2.Callback<T> {

private var isSuccessful = false
var onSuccess: ((T?) -> Unit)? = null
var onSuccessWithHeaders: ((T?, HashMap<String, String>) -> Unit)? = null
var onNetworkError: (() -> Unit)? = null
var onServerError: ((String?, String?) -> Unit)? = null
var onFinish: ((Boolean?) -> Unit)? = null
var onUnauthorized: (() -> Unit) = {

// app.goToLogin() }

override fun onResponse(call: Call<T>, response: Response<T>) {
    if (response.isSuccessful) {
        isSuccessful = true
        onSuccess?.invoke(response.body())
        response.headers()
        onSuccessWithHeaders?.invoke(response.body(), getHeaders(response.headers()))

    } else {
        val errorResponse = getErrorResponse(response)
        when (response.code()) {
            401 -> onUnauthorized()
            500 -> {
                onServerError?.invoke(errorResponse?.codigo, errorResponse?.descripcion)
            }
            else -> {
                onServerError?.invoke(errorResponse?.codigo, errorResponse?.descripcion)
            }
        }
    }
    onFinish?.invoke(isSuccessful)
}

override fun onFailure(call: Call<T>, t: Throwable) {
    onNetworkError?.invoke()
    onFinish?.invoke(isSuccessful)
}

private fun getErrorResponse(response: Response<T>): ErrorResponse? {
    try {
        return GsonConverterFactory.create().responseBodyConverter(
            ErrorResponse::class.java!!,
            arrayOfNulls(0),
            null
        )?.convert(response.errorBody()!!) as ErrorResponse?
    } catch (e: IOException) {
        e.printStackTrace()
    }

    return null
}

private fun getHeaders(headers: Headers): HashMap<String, String> {
    val result = HashMap<String, String>()
    for (i in 0 until headers.size()) {
        result[headers.name(i)] = headers.value(i)
    }
    return result
}

}

Inside the Java class i tried this but no luck:

First i declared it:

private Callback<String> entidadesHabilitadasCallback = new Callback<String>((NetworkApplication)this);

and then i am trying to do something like this:

entidadesHabilitadasCallback.setOnSuccess();

But i have to put there a parameter and i dont know what to write.

Kotlin Java has interop with lambda function , it is same as SAM conversion in java.

You can define/set it like this:

entidadesHabilitadasCallback.setOnSuccess(it -> {
    // use it, do something
    return Unit.INSTANCE;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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