如何使用 vavr 返回 void 或字符串

EFO*_*FOE 5 java vavr

我有一个函数,当某些条件不满足时,它应该不返回任何内容( void )或字符串。

我尝试这条线 Either.left(Void)

    private Either<Void,String> processOrReturnErrorMessage(){
        //Do something  and in some case return a message of failed conditions
        return Either.left(Void);
    }
Run Code Online (Sandbox Code Playgroud)

Nán*_*ete 6

vavr 中有一个类型,它被称为Option. Option.none()如果没有错误可以返回,Option.some(errorMessage)如果有错误则可以返回。

如果您仍然想使用Either,我建议使用左侧表示错误,使用右侧表示值(快乐路径),因为Either右偏的,因此map和方法仅在它是正确flatMap值时才起作用。在您的情况下,由于没有要返回的值(即 void),因此您可以使用, 并 return来表示成功,因为是该类型的唯一居民(null 是 Java 中所有非原始类型的居民,截至现在,不幸的是)。EitherEither<String, Void>Either.right(null)nullVoid

Unit或者,您可以引入一种用单个居民(即单例)调用的新类型,Either<String, Unit>用于您的返回类型并返回Either.right(Unit.instance())以表示缺乏有意义的返回值并避免返回null值,因为返回null值有点难看。