Kotlin type inference compile error when using Akk

2019-08-12 08:44发布

问题:

I want to use Akka java API in a Kotlin program. When i want to set onComplete callback for a akka Future, i encounter the Kotlin compiler error, while the java equivalent work nice:

val future: Future<Any> = ask(sender, MyActor.Greeting("Saeed"), 5000)

future.onComplete(object : OnComplete<Object>() {
    override fun onComplete(failure: Throwable?, success: Object?) {
        throw UnsupportedOperationException()
    }
}, context.dispatcher())

The java code:

Future<Object> future = ask(sender(), new MyActor.Greeting("Saeed"), 5000);

future.onComplete(new OnComplete<Object>() {
    public void onComplete(Throwable failure, Object result) {
        if (failure != null) {
            System.out.println("We got a failure, handle it here");
        } else {
            System.out.println("result = "+(String) result);
        }
    }
},context().dispatcher());

The Kotlin compiler error:

Error:(47, 24) Kotlin: Type inference failed: 
fun <U : kotlin.Any!> onComplete(p0: scala.Function1<scala.util.Try<kotlin.Any!>!, U!>!, p1: scala.concurrent.ExecutionContext!): 
kotlin.Unit cannot be applied to (<no name provided>,scala.concurrent.ExecutionContextExecutor!)
Error:(47, 35) Kotlin: Type mismatch: inferred type is <no name provided> but scala.Function1<scala.util.Try<kotlin.Any!>!, scala.runtime.BoxedUnit!>! was expected

I pushed the project to github.

回答1:

Well, the error message may be a bit unclear because of a lot of Scala stuff and <no name provided>, but it clearly defines the point of the error: your function should accept an Any, not an Object. The following codes compiles without any problems:

val future: Future<Any> = ask(sender, MyActor.Greeting("Saeed"), 5000)

future.onComplete(object : OnComplete<Any?>() {
    override fun onComplete(failure: Throwable?, success: Any?) {
        throw UnsupportedOperationException()
    }
}, context.dispatcher())