简体   繁体   English

对 By/BySelector 使用 Optional 的空检查

[英]Null check using Optional for By/BySelector

I want to re-write my null checking code, and use Optional instead.我想重写我的空检查代码,并使用 Optional 代替。

public BySelector select(BySelector bySelector, Boolean value) {
  return (bySelector == null) ? By.checkable(value) : bySelector.checkable(value);
}

The above is my original code.以上是我的原始代码。 I have no idea how to replace to Optional.我不知道如何替换为 Optional。 I've tried the following but it is not working.我已经尝试了以下但它不起作用。 Please advise.请指教。 Thank you.谢谢你。

public BySelector select(BySelector bySelector, Boolean value) {
  return Optional.ofNullable(bySelector.checkable(value).orElse(By.checkable(value);
}

There is no need to use Optional in your case as it is less clear than your simple null check, but this is how I would do :在您的情况下无需使用 Optional ,因为它不如您的简单空检查清楚,但这就是我要做的:

Optional.ofNullable(bySelector)
        .map(x -> By.checkable(value))
        .orElse(BySelector.checkable(value));

Maybe you want your method to return an optional, which makes more sense.也许你希望你的方法返回一个可选的,这更有意义。

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

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