繁体   English   中英

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

[英]Scala RxJava argument expression's type is not compatible with formal parameter type

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

我在将匿名类传递给RxJava map方法时遇到错误

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中的map方法签名:

@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
    }
  })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM