问题描述
我对如何正确执行此操作"感到困惑:
I am a little confused on "how to do this properly":
// return true: if present and number of lines != 0
boolean isValid(Optional<File> optFile) {
return optFile.ifPresentOrElse(f -> return !isZeroLine(f), return false);
}
private boolean isZeroLine(File f) {
return MyFileUtils.getNbLinesByFile(f) == 0;
}
我知道语法不正确且无法编译,但这仅是您了解的主意.
I know the syntax is not correct and not compiling, but it's just for you to get the idea.
如何将其转换为干净的代码"?即避免这样做:
How can I turn this into 'clean code'?i.e. avoid doing:
if (optFile.isPresent()) {//} else {//}
推荐答案
处理布尔值返回类型(很容易推断出 Predicate
s),一种方法是使用 Optional.filter :
Dealing with boolean return type(easily inferred Predicate
s), one way to do that could be to use Optional.filter
:
boolean isValid(Optional<File> optFile) {
return optFile.filter(this::isZeroLine).isPresent();
}
但是,然后使用 Optional
s参数似乎是一种不好的做法.正如卡洛斯(Carlos)的评论所建议的那样,另一种实现方式可能是:
But, then using Optional
s arguments seems to be a poor practice. As suggested in comments by Carlos as well, another way of implementing it could possibly be:
boolean isValid(File optFile) {
return Optional.ofNullable(optFile).map(this::isZeroLine).orElse(false);
}
另一方面, ifPresentOrElse
是一种结构,用于执行与 Optional
值之类的存在对应的某些操作,例如:
On another note, ifPresentOrElse
is a construct to be used while performing some actions corresponding to the presence of the Optional
value something like :
optFile.ifPresentOrElse(this::doWork, this::doNothing)
相应的动作可能是-
private void doWork(File f){
// do some work with the file
}
private void doNothing() {
// do some other actions
}
这篇关于返回布尔值的Java 10 ifPresentOrElse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!