类型推断失败预期的类型不匹配

问题描述

以下代码显示错误。类型推断失败。预期的类型不匹配必需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>>