java - Constructor with Optional<String> -


i have written following code:

void test(a a) {    b b = new b(a.getname()); } 

so, constructor of b expects string. looks following:

protected b (string name) {     super(name, kind);     this.name = name; } 

but a.getname() gives me name optional<string> return value , not want change that. therefore, try change parameter of constructor b (i replace string name optional<string>), eclipse underlines super(name, kind) , this.name = name red , eclipse recommends change parameter of constructor again string name.

how can solve it?

best regards,

an optional<string> might contain string, need check (and speaking, handle case absent). test() method might this:

void test(a a){  // consider adding a.getname().ispresent() check , handling false  // case if need to.  otherwise you'll illegalstateexception.  b b = new b (a.getname().get()); } 

in general, better practice leave constructor parameter string, , convert n optional<string> when store it.

the alternative, if want users pass in optionals, make sense, fix super() constructor take optional<string>. if can't that, need call .get() , pass resulting string super(); again handling absent case needed.


Comments