简体   繁体   English

使用 Flux.handle() 时如何指定 generics

[英]How to specify the generics when using Flux.handle()

As title, I don't know how to specify the generics when I using Flux.handle() .作为标题,当我使用Flux.handle()时,我不知道如何指定 generics 。 It will return a Flux<Object> after the handle() method like below example.它将在handle()方法之后返回一个Flux<Object> ,如下例所示。

Flux.range(0, 10) // 1
        .handle((x, sink) -> {
            if (x % 2 == 0)
                sink.next(x);
        }) // 2
        .map(o -> Integer.valueOf(o.toString()))
        .subscribe(System.out::println);

It's a simple example to express the problem I'm facing so please don't care whether the content could be better.这是一个简单的例子来表达我面临的问题,所以请不要关心内容是否可以更好。

The IDE shows Flux<Integer> at 1 and Flux<Object> at 2, so I need to add a map() method to transform the type which I want to use. IDE 显示Flux<Integer>在 1 和Flux<Object>在 2,所以我需要添加一个map()方法来转换我想要使用的类型。

Is there any way to specify the return type without using map() ?有没有办法在不使用map()的情况下指定返回类型?

You can use a type witness:您可以使用类型见证:

Flux.range(0, 10)
    .<Integer>handle((x, sink) -> {
        if (x % 2 == 0)
            sink.next(x);
    });

This resolves to Flux<Integer>这解析为Flux<Integer>

This is a deficiency in Java's type inference, rather than a specific flaw of this class.这是 Java 类型推断的缺陷,而不是 class 的特定缺陷。 Type witnesses are Java's way of explicitly declaring the generic type parameters, rather than relying on them being inferred.类型见证是 Java 显式声明泛型类型参数的方式,而不是依赖于它们被推断。

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

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