java如何使用vavr返回void或字符串
我有一个函数,当某些条件不满足时,它应该不返回任何内容(void)或字符串
我也试试这一行。左(空)
private Either<Void,String> processOrReturnErrorMessage(){
//Do something and in some case return a message of failed conditions
return Either.left(Void);
}
# 1 楼答案
在vavr中有一种类型,叫做
Option
。如果没有错误,可以返回Option.none()
,如果有错误,可以返回Option.some(errorMessage)
如果您仍然想使用
Either
,我建议使用左侧表示错误,使用右侧表示值(快乐路径),因为Either
是右偏,因此map
和flatMap
方法仅在Either
是右值时才对其起作用。在您的例子中,由于没有要返回的值(即一个空值),您可以使用Either<String, Void>
,并为成功案例返回Either.right(null)
,因为null
是类型Void
的唯一驻留者(很遗憾,到目前为止,null是Java中所有非原始类型的驻留者)或者,您可以引入一个名为
Unit
的新类型,使用Either<String, Unit>
作为返回类型,使用Either.right(Unit.instance())
来表示缺少有意义的返回值,并避免返回null
值,因为返回null
值有点难看