【问题标题】:Lambda function without parameters - Cannot infer functional interface type没有参数的 Lambda 函数 - 无法推断函数接口类型
【发布时间】:2021-01-13 08:54:15
【问题描述】:

我有一个不需要任何参数的 lambda 函数:

Observable.interval(5, TimeUnit.SECONDS)
  .subscribe(x -> new CryptoCompareRxService().getHistoricalDaily("BTC", "USD")
    .subscribe(historicalDaily -> System.out.println("historicalDaily = " + historicalDaily)));

我想用“()”替换“x”,因为它没用:

Observable.interval(5, TimeUnit.SECONDS)
  .subscribe(() -> new CryptoCompareRxService().getHistoricalDaily("BTC", "USD")
    .subscribe(historicalDaily -> System.out.println("historicalDaily = " + historicalDaily)));

但是当我这样做时,我得到一个错误:

无法推断功能接口类型

为什么?

这是完整的课程:

package com.tests.retrofitrxjava;

import com.tests.retrofitrxjava.rx.CryptoCompareRxService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import rx.Observable;

import java.util.concurrent.TimeUnit;

@SpringBootApplication
public class RetrofitRxjavaApplication {

  public static void main(String[] args) {

    SpringApplication.run(RetrofitRxjavaApplication.class, args);

    Observable.interval(5, TimeUnit.SECONDS)
      .subscribe(x -> new CryptoCompareRxService().getHistoricalDaily("BTC", "USD")
        .subscribe(historicalDaily -> System.out.println("historicalDaily = " + historicalDaily)));

  }

}

【问题讨论】:

  • Java 需要一个函数式接口 with 一个参数,因为无论你是否想要它都会传递一个参数。否则,您只是在为程序引入不正确的语义——类似于尝试调用((Runnable) r).run(42)——将参数传递给采用 void 的方法。丢弃参数(您不使用的参数)是处理该问题的常用方法。在许多语言中,_ 表示丢弃,但 Java is a special case as it doesn't allow it

标签: java spring-boot lambda rx-java rx-java2


【解决方案1】:

我认为你的错误是由于版本 2 中的 RX Observable 发生变化,现在订阅接受 Consumer 接受参数

public final Disposable subscribe(Consumer<? super T> onNext)

消费者 接受单个值的功能接口(回调)。

而不是版本 1 中的 Action

public final Subscription subscribe(Action1<? super T> onNext)

动作1 扩展动作 单参数操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    相关资源
    最近更新 更多