Scala RxJava 参数表达式的类型与形式参数类型不兼容



我试图使用RxJava库和Scala语言使用Vertx工具链实现简单的websocket处理。

而且我在将匿名类传递给 RxJavamap方法时出错

websocket
.flatMap(socket => socket.toObservable)
.map(new Function[Buffer, String] {
override def apply(msg: Buffer): String = {
msg.toString
}
})

编译器堆栈跟踪:

Error:(61, 6) no type parameters for method map: (x$1: io.reactivex.functions.Function[_ >: io.vertx.reactivex.core.buffer.Buffer, _ <: R])io.reactivex.Observable[R] exist so that it can be applied to arguments (io.reactivex.functions.Function[io.vertx.reactivex.core.buffer.Buffer,String])
--- because ---
argument expression's type is not compatible with formal parameter type;
found   : io.reactivex.functions.Function[io.vertx.reactivex.core.buffer.Buffer,String]
required: io.reactivex.functions.Function[_ >: io.vertx.reactivex.core.buffer.Buffer, _ <: ?R]
Note: io.vertx.reactivex.core.buffer.Buffer <: Any, but Java-defined trait Function is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
.map(new Function[Buffer, String] {

Error:(61, 10) type mismatch;
found   : io.reactivex.functions.Function[io.vertx.reactivex.core.buffer.Buffer,String]
required: io.reactivex.functions.Function[_ >: io.vertx.reactivex.core.buffer.Buffer, _ <: R]
.map(new Function[Buffer, String] {

RxJava 中的映射方法签名:

@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> Observable<R> map(Function<? super T, ? extends R> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new ObservableMap<T, R>(this, mapper));
}

在编译器堆栈跟踪中,我看到函数收到下限Buffer并且它应该工作,但它没有。

如何解决将右lambda传递给函数map编译时问题?

尝试指定类型参数:

websocket
.flatMap(socket => socket.toObservable)
.map[String]((msg: Buffer) => {
msg.toString
})

websocket
.flatMap(socket => socket.toObservable)
.map[String](new Function[Buffer, String] {
override def apply(msg: Buffer): String = {
msg.toString
}
})

最新更新