我使用扩展功能来扩展retrofit2.Response
对象:
摘要:
public class ErrorResponse {
private int code;
private String message;
private Response response;
}
import okhttp3.MediaType
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.ResponseBody
import retrofit2.Response
fun Response<*>.errorResponse(): ErrorResponse {
val errorResponse = ErrorUtils.parseError(this)
return errorResponse
}
在这里使用:
viewModelScope.launch(Dispatchers.Main) {
val response: Response<*> = TransportService.getTraidersList()
if (response.isSuccessful) {
finishLoadData()
val traders: List<Trader> = response.body() as List<Trader>
traderListLiveData.postValue(traders)
} else {
val errorResponse = response.errorResponse()
val message = errorResponse.message // here use extension function
messageLiveData.value = SingleEvent(message)
}
}
好。很好。
但是我想使用扩展属性。我试试这个:
val Response<*>.errorResponse: ErrorResponse {
get() = ErrorUtils.parseError(this)
}
但是我得到了编译错误:
Function declaration must have a name Unresolved reference: get
答案 0 :(得分:1)
属性不需要括号。可能看起来像这样:
val Response<*>.errorResponse: ErrorResponse
get() = ErrorUtils.parseError(this)