反应堆中 vavr Either 的意外返回类型

问题描述 投票:0回答:2

使用 vavr 的 Either 有两种简单的方法。

public Either<String, Integer> testEither(int s) {
    if (s == 0)
        return Either.left("Wrong");
    return Either.right(s);
}

public Mono<Either<String, Integer>> testReactorEither(int s) {
    return Mono.just(s).filter(x -> x == 0).map(Either::right)
            .switchIfEmpty(Mono.just(Either.left("ERROR")));
}

testEither
工作正常,但同时,
testReactorEither
引发“不兼容类型”的编译错误,表示提供的
reactor.core.publisher.Mono<io.vavr.control.Either<java.lang.Object,java.lang.Integer>>
返回类型与
reactor.core.publisher.Mono<io.vavr.control.Either<java.lang.String,java.lang.Integer>>
所需的返回不兼容。

恐怕问题只是因为

map(Either::right)
的方法只定义了
Right
Integer
类型,但没有定义
Left
类型,然后该方法的返回类型是
Either<?, Integer>
。那么问题是在这种情况下我如何才能得到预期的返回类型?

[已更新]

正如 Hinse 在评论中提到的,该问题与 Java 类型推断的限制有关,我找到的有关该问题的一些链接如下:

https://bugs.eclipse.org/bugs/show_bug.cgi?id=511252

https://e.printstacktrace.blog/java-type-inference-generic-methods-chain-call/

https://openjdk.java.net/jeps/101

java spring-webflux project-reactor vavr
2个回答
1
投票

当应用

map(Either::right)
时,第二个示例似乎“丢失”了左侧的类型信息。

在映射方法调用中添加一些类型“提示”应该可以解决问题。所以 testReactorEither 看起来像这样:

public Mono<Either<String, Integer>> testReactorEither(int s) {
    return Mono.just(s)
            .filter(x -> x == 0)
            .<Either<String, Integer>>map(Either::right)
            .switchIfEmpty(Mono.just(Either.left("ERROR")));
}

0
投票

没有 meu caso tomei o 错误:无法访问 io.vavr.control.Either...

e como estava usando gerenciador de módulos .gradle,adicionei no meu pacote/modulo de基础设施à dependentência实现('io.vavr:vavr:0.10.4'),rodei或重新加载do gradle和resolve。

© www.soinside.com 2019 - 2024. All rights reserved.