Main Question: How can I override kotlin method in java which returns Unit type?
I'm trying to use kotlin library in java and there is a method which name is override fun invoke(): Unit that I have to implement.
but, java compiler keep telling me return type void is not compatible with Unit.
I tried public Unit invoke() { return Unit.INSTANCE; } in java but occurs compile error.
invoke()' in 'myproject' clashes with 'invoke()' in 'library';
attempting to use incompatible return type
kotlin interface (in library)
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 abstract class (in my project)
public abstract class AbstractMessageHandler<T extends Message> implements MessageHandler<T> {
@Override
public void invoke(@NotNull Message message) {
//this is where the compile error occurs.
}
}
error message
(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
voidas the return type and there is no error. - Sweeper