[英]How to override Any parameter in Kotlin with Java Object?
I'm writing a retrofit implementation and I have the following interface method:我正在编写一个 retrofit 实现,我有以下接口方法:
suspend fun uploadAvatar(file: Any, sessionToken: String)
In my impelementation I'm trying to override the 'file' parameter as a MultipartBody.Part object:在我的实现中,我试图将“文件”参数覆盖为 MultipartBody.Part object:
override suspend fun uploadAvatar(file: MultipartBody.Part, sessionToken: String)
and I'm getting the following error:我收到以下错误:
I can see that okhttp3 is written in Java and I'm assuming that's the reason for the error.我可以看到 okhttp3 写在 Java 中,我假设这就是错误的原因。 If so how do I get around it?
如果是这样,我该如何解决? Otherwise what else could be going on?
否则还会发生什么?
It's not because it's written in Java. It's because you're trying to violate the interface contract by narrowing the type of an input parameter.这不是因为它写在 Java 中。这是因为您试图通过缩小输入参数的类型来违反接口契约。 The interface declares that
file
can be anything because it is of type Any.该接口声明
file
可以是任何类型,因为它是 Any 类型。 If the compiler let you narrow a type definition, then your class would be able to call functions specific to MultipartBody.Part
on file
, but then pass an instance of your class as the interface type, and some other code could pass a different class type to your function as file
, which doesn't make sense.如果编译器允许您缩小类型定义,那么您的 class 将能够调用
file
上特定于MultipartBody.Part
的函数,然后将您的 class 的实例作为接口类型传递,而其他一些代码可以传递不同的 class 类型到您的 function 作为file
,这没有意义。
I can't suggest how to avoid this problem because you didn't say how you're using your interface.我不能建议如何避免这个问题,因为你没有说你是如何使用你的界面的。 I don't see what it really has to do with Retrofit.
我看不出它与 Retrofit 有什么关系。
In general, this kind of problem might be solved using generics, but that would only apply to some use cases.通常,使用 generics 可能会解决此类问题,但这仅适用于某些用例。 Example:
例子:
interface Foo<in T> {
suspend fun uploadAvatar(file: T, sessionToken: String)
}
class MyFooBodyImpl: Foo<MultipartBody.Part> {
suspend fun uploadAvatar(file: MultipartBody.Part, sessionToken: String) {
TODO()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.