如何使用 Java 对象覆盖 Kotlin 中的任何参数?
我正在编写一个改造实现,并且有以下接口方法:
suspend fun uploadAvatar(file: Any, sessionToken: String)
在我的实现中,我试图将“文件”参数重写为 MultipartBody.Part 对象:
override suspend fun uploadAvatar(file: MultipartBody.Part, sessionToken: String)
并且出现以下错误:
我可以看到okhttp3 是用 Java 编写的,我假设这就是错误的原因。如果是这样我该如何解决它?否则还能发生什么?
I'm writing a retrofit implementation and I have the following interface method:
suspend fun uploadAvatar(file: Any, sessionToken: String)
In my impelementation I'm trying to override the 'file' parameter as a 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. If so how do I get around it? Otherwise what else could be going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这并不是因为它是用 Java 编写的。这是因为您试图通过缩小输入参数的类型来违反接口约定。该接口声明
file
可以是任何内容,因为它的类型为 Any。如果编译器允许您缩小类型定义范围,那么您的类将能够在file
上调用特定于MultipartBody.Part
的函数,然后将类的实例传递为接口类型和其他一些代码可以将不同的类类型作为file
传递给您的函数,这是没有意义的。我无法建议如何避免此问题,因为您没有说明如何使用界面。我不明白这与改造有什么关系。
一般来说,此类问题可以使用泛型来解决,但这仅适用于某些用例。例子:
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. The interface declares that
file
can be anything because it is of type Any. If the compiler let you narrow a type definition, then your class would be able to call functions specific toMultipartBody.Part
onfile
, 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 asfile
, which doesn't make sense.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.
In general, this kind of problem might be solved using generics, but that would only apply to some use cases. Example: