下面的代码显示该错误。类型推断失败。预期类型不匹配必需:Response<BaseResponse<Any>>! 找到了:Response<BaseResponse<RetriveUserInfoResponse>!>!

`when`( mockIOnboardingService.validateCustomerIdentity(customerType.toLowerCase(), ValidateCustomerRequest(customerId, documentType, "243546", tyc)))
.thenReturn(Response.success(BaseResponse(payload = RetriveUserInfoResponse("+5689765432")))) //--> Here the error
这是validateCustomerIdentity方法
@POST(ApiConstants.bffOnboardingPath + ApiConstants.pathRetriveUserInfo)
    suspend fun validateCustomerIdentity(
        @Header(ApiConstants.headerXflowService) customerType : String,
        @Body body: ValidateCustomerRequest
    ): Response<BaseResponse<Any>>
如您所见,它返回BaseResponse<Any>。为什么Android Studio向我显示BaseResponse<RetriveUserInfoResponse>!错误
这是RetrieveUserInfoResponse数据类
data class RetriveUserInfoResponse(
    @SerializedName("phone")
    val phone: String
)

最佳答案

这个问题是Response.success(BaseResponse(payload = RetriveUserInfoResponse("+5689765432")))生成了Response<BaseResponse<RetriveUserInfoResponse>>,它与Response<BaseResponse<Any>>的类型(或子类型)不同。
您可以通过将RetriveUserInfoResponse转换为Any来解决此问题:

Response.success(BaseResponse(payload = RetriveUserInfoResponse("+5689765432") as Any))
或者通过将validateCustomerIdentity()的返回类型更改为Response<out BaseResponse<out Any>>,这是可行的,因为Response<BaseResponse<RetriveUserInfoResponse>>Response<out BaseResponse<out Any>>的子类:
@POST(ApiConstants.bffOnboardingPath + ApiConstants.pathRetriveUserInfo)
suspend fun validateCustomerIdentity(
    @Header(ApiConstants.headerXflowService) customerType : String,
    @Body body: ValidateCustomerRequest
): Response<out BaseResponse<out Any>>

10-05 18:53