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

时间:2018-10-08 20:44:00

标签: scala rx-java2 vert.x

我试图使用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函数的编译时问题?

1 个答案:

答案 0 :(得分:0)

尝试指定类型参数:

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