簡體   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