【问题标题】:How can I assign a value to an int variable with optional?如何为可选的 int 变量赋值?
【发布时间】: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 -&gt; this.x = x);,但这并不比惯用的if(point.getX() != null) this.x = point.getX();更干净

标签: java java-8 optional


【解决方案1】:

你必须使用Integer而不是原始类型int

您没有发布足够的代码,但您的 getX 方法定义应该是:

Optional&lt;Integer&gt; getX() 而不是int getX()

如果你不能用方法修改类,创建一个包装类什么的。没有看到所有代码,我不能多说……

编辑:

让你的点类存储可选值:

class Point
{
    private Optional<String> x;
    private Optional<String> y;

    public Optional<String> getX () { //Here can not use Optional<String>
        return this.x;
    }

    public Optional<String> getY () {
        return this.y;
    }

    public Point(String x, String y) {
        this.x = ofNullable(x);
        this.y = ofNullable(y);
    }
}

然后:

Point point = new Point(null, "14.2");

if(point.getX().isPresent()) {
  this.xCoordinate = point.getX();
}

if(point.getY().isPresent()) {
  this.yCoordinate = point.getY();
}

【讨论】:

  • 我扩展了代码,希望现在清楚我想要什么。
  • 我在那里评论过我不想让它们成为可选的。
猜你喜欢
  • 1970-01-01
  • 2018-05-06
  • 1970-01-01
  • 2016-03-17
  • 1970-01-01
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 2014-07-03
相关资源
最近更新 更多