【发布时间】:2021-03-02 02:21:16
【问题描述】:
主要问题:如何在 java 中覆盖返回 Unit 类型的 kotlin 方法?
我正在尝试在 java 中使用 kotlin 库,我必须实现一个名为 override fun invoke(): Unit 的方法。
但是,java 编译器一直告诉我return type void is not compatible with Unit。
我在java中尝试了public Unit invoke() { return Unit.INSTANCE; },但出现编译错误。
invoke()' in 'myproject' clashes with 'invoke()' in 'library';
attempting to use incompatible return type
kotlin 接口(在库中)
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
【问题讨论】:
-
你能显示minimal reproducible example吗?我使用
void作为返回类型,没有错误。 -
@Sweeper,我添加了示例。谢谢!
标签: java kotlin overriding