【发布时间】:2020-03-03 17:45:57
【问题描述】:
例如,我有这样的代码:
class Point
{
private String x;
private String y;
public String getX () { //Here can not use Optional<String>
return this.x;
}
public String getY () {
return this.y;
}
public Point(String x, String y) {
this.x = x;
this.y = y;
}
}
...
Point point = new Point(null, "14.2");
if(ofNullable(point.getX().isPresent()) {
this.xCoordinate = point.getX();
}
if(ofNullable(point.getY().isPresent()) {
this.yCoordinate = point.getY();
}
我想以更简洁的方式来做,像这样:
this.x = ofNullable(point.getX()).ifPresent((x) -> x)
我知道这不起作用,但我几乎尝试了所有方法,但无法让它起作用。
【问题讨论】:
-
ofNullable(point.getY().isPresent()有点混乱。getY()是否返回可选项?或者你是在point上创建一个可选的? -
这里的括号不匹配。
-
@ernest_k 我编辑了代码。有这些条件可以吗?
-
您可以使用
ofNullable(point.getX()).ifPresent(x -> this.x = x);,但这并不比惯用的if(point.getX() != null) this.x = point.getX();更干净