具有可选< String> [英] Constructor with Optional<String>

查看:141
本文介绍了具有可选< String>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码:

void Test(A a) {
   B b = new B(a.getName());
}

因此, B 期望一个 String 。它如下所示:

So, the constructor of B expects a String. It looks like the following:

protected B (String name) {
    super(name, KIND);
    this.name = name;
}

a.getName()给我一个名称,可选< String> 作为返回值,我不想改变。因此,我尝试改变构造函数 B 的参数(用替换 String name 可选< String> ),但是Eclipse强调 super(name,KIND) this.name = name 用红色和Eclipse建议再次将构造函数的参数更改为 String name

But a.getName() gives me a name with Optional<String> as return value and I do not want to change that. Therefore, I try to change the parameter of the constructor B (I replace String name with Optional<String>), but then Eclipse underlines super(name, KIND) and this.name = name with red and Eclipse recommends to change the parameter of the constructor again to String name.

如何解决?

最好的问候,

推荐答案

可选< String> 可能包含 String ,因此您需要检查并且一般来说,处理其不存在的情况)。因此,您的 Test()方法可能如下所示:

An Optional<String> might contain a String, so you need to check for that (and generally speaking, handle the case where it is absent). So your Test() method might look like this:

void Test(A a){
 // Consider adding a a.getName().isPresent() check and handling the false
 // case if you need to.  Otherwise you'll get an IllegalStateException.
 B b = new B (a.getName().get());
}

通常,更好的做法是将构造函数参数保留为 String ,然后将其转换为可选< String>

In general, the better practice is to leave your constructor parameter as a String, and then convert it into a n Optional<String> when you store it.

另一种方法是,如果你真的希望用户传递可选,这有时是有意义的,是修复 super ()构造函数也接受可选< String> 。如果你不能这样做,你需要类似地调用 .get()并将结果 String code> super();再次根据需要处理不存在的情况。

The alternative, if you really want users to pass in Optionals, which does sometimes make sense, is to fix the super() constructor to also take an Optional<String>. If you can't do that, you need to similarly call .get() and pass the resulting String into super(); again handling the absent case as needed.

这篇关于具有可选&lt; String&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆