如何使用 Java 对象覆盖 Kotlin 中的任何参数?

发布于 2025-01-16 04:58:00 字数 490 浏览 2 评论 0原文

我正在编写一个改造实现,并且有以下接口方法:

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:

error message

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沫尐诺 2025-01-23 04:58:00

这并不是因为它是用 Java 编写的。这是因为您试图通过缩小输入参数的类型来违反接口约定。该接口声明 file 可以是任何内容,因为它的类型为 Any。如果编译器允许您缩小类型定义范围,那么您的类将能够在 file 上调用特定于 MultipartBody.Part 的函数,然后将类的实例传递为接口类型和其他一些代码可以将不同的类类型作为 file 传递给您的函数,这是没有意义的。

我无法建议如何避免此问题,因为您没有说明如何使用界面。我不明白这与改造有什么关系。

一般来说,此类问题可以使用泛型来解决,但这仅适用于某些用例。例子:

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()
    }
}

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 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.

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:

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()
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文