gpt4 book ai didi

java - 我可以覆盖在 Java 中返回 Unit 类型的 kotlin 方法吗

转载 作者:行者123 更新时间:2023-12-04 15:04:25 25 4
gpt4 key购买 nike

主要问题:如何在返回 Unit 类型的 java 中覆盖 kotlin 方法?
我正在尝试在 java 中使用 kotlin 库,并且有一个名称为 override fun invoke(): Unit 的方法我必须实现。
但是,java 编译器一直告诉我 return type void is not compatible with Unit .
我试过 public Unit invoke() { return Unit.INSTANCE; }在java中但发生编译错误。

invoke()' in 'myproject' clashes with 'invoke()' in 'library'; 
attempting to use incompatible return type

kotlin 接口(interface)(在库中)
interface MessageHandler<M : Message> : (Message) -> Unit {

override fun invoke(message: Message): Unit =
if (messageType.isAssignableFrom(message.javaClass)) {
println("invoked ${message.javaClass.simpleName}")
} else {
throw IllegalArgumentException("Unsupported message type ${message.javaClass.simpleName}")
}

}
java抽象类(在我的项目中)
public abstract class AbstractMessageHandler<T extends Message> implements MessageHandler<T> {

@Override
public void invoke(@NotNull Message message) {
//this is where the compile error occurs.
}
}
错误信息
(Message) in AbstractMessageHandler cannot implement invoke(P1) in Function1
public void invoke(@NotNull Message message) {
^
return type void is not compatible with Unit
where P1,R are type-variables:
P1 extends Object declared in interface Function1
R extends Object declared in interface Function1

最佳答案

看起来像一个 4 年前 Unresolved 错误:https://youtrack.jetbrains.com/issue/KT-15964
引:

I don't think this is possible now because ofcompatibility with older binaries. We'll see what we can do, thank youfor the report.

An ugly workaround would be to use the nullable type Unit?:

interface TestA<out T> {
fun foo(): T
}

abstract class TestB : TestA<Unit?> {
override fun foo(): Unit? {
// ...
return Unit
}
}

With this, you won't be required to override foo in a Java subclass.If you want to override it though, the signature in the Java subclassshould be public Unit foo().


如果你不控制图书馆,我不确定你能做多少。

关于java - 我可以覆盖在 Java 中返回 Unit 类型的 kotlin 方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66432386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com