
我有大約 20 個檔案,看起來像上圖中的紅色和藍色部分,現在我想為所有檔案添加
private val requestDataSource: RequestDataSource引數(綠色第 15 行)并呼叫requestDataSource.post() (綠色第 20 行)。
我嘗試使用自定義引數 P、自定義回傳型別 RET 和函式引數創建一個通用函式,這樣我就可以像在sendEz函式中一樣使用它,但它不起作用。
我在函式引數上遇到錯誤:
型別不匹配。必需:(TypeVariable(P)) → ApiRequestResponse<TypeVariable(RET)> 發現:布爾函式呼叫 'send(...)' 預期
我不明白,我不想在第 30m 行呼叫它,同時它看起來被視為已呼叫,因為 found 引數是布林值(的回傳型別service.sen(emnail)),但我沒有在那里呼叫它。 ..
這是可以實作的嗎?如果是這樣,怎么做?
代碼在這里:
class EmailDataSource @Inject constructor(
private val dao: EmailDao,
private val service: EmailService,
private val requestDataSource: RequestDataSource,
): BaseDataSource<EmailModel, EmailDataModel>(dao) {
suspend fun send(email: EmailModel): ApiRequestResponse<Boolean> {
return try {
val response = service.send(email)
requestDataSource.post()
ApiRequestResponse.Success(response)
} catch (e: Throwable) {
val ioe = IOException("Error sending email", e)
Timber.w(ioe)
ApiRequestResponse.Error(ioe)
}
}
suspend fun sendEz(email: EmailModel): ApiRequestResponse<Boolean> {
return call<EmailModel, Boolean>(service.send, email, "Error sending email")
}
suspend fun <P: Any, RET: Any> call(
function: (parameter: P) -> ApiRequestResponse<RET>,
parameter: P,
error: String = "Error making the request"
): ApiRequestResponse<RET> {
return try {
val response = function(parameter)
requestDataSource.post()
response
} catch (e: Throwable) {
val ioe = IOException(error, e)
Timber.w(ioe)
ApiRequestResponse.Error(ioe)
}
}
}
解決方案:
protected suspend fun <P: Any, RET: Any> call(
function: KSuspendFunction1<P, RET>,
parameter: P,
error: String = "Error making the request"
): ApiRequestResponse<RET> {
val result = function(parameter) // call the function
}
/** And call it like this */
suspend fun get(param: String, param2: Boolean): ApiRequestResponse<WHAT service::get RETURNS> {
return call(service::get, param, param2, "Error message")
}
/** Where service is the retrofit interface */
@GET("Endpoint/{date}/{includeStops}")
suspend fun get(
@Path("date") date: String,
@Path("stops") stops: Boolean
): List<Model>
uj5u.com熱心網友回復:
A.是呼叫它的語法。::僅用于傳遞對函式的參考。
所以嘗試把service::send而不是service.send
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/426686.html
下一篇:使用反射和泛型改進代碼
