使用Akka Java API时Kotlin类型推断编译错误
问题描述:
我想在Kotlin程序中使用Akka Java API。当我想为akka Future
设置akka onComplete
回调时,我遇到Kotlin编译器错误,而Java等效工作不错:
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())
java代码:
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());
Kotlin编译器错误:
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
我将项目推送到 github 。
答
嗯,错误消息可能由于很多Scala内容和<未提供名称>
而不清楚,但是它清楚地定义了错误点:您的函数应接受任何
,而不是对象
。下列代码可以毫无问题地编译:
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())