user3097712
user3097712

Reputation: 1675

Constructor with Optional<String>

I have written the following code:

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

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

protected B (String name) {
    super(name, KIND);
    this.name = 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.

How can I solve it?

best regards,

Upvotes: 0

Views: 425

Answers (2)

Zymus
Zymus

Reputation: 1698

You could make another constructor that takes aan Optional.

Upvotes: 0

dimo414
dimo414

Reputation: 48864

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());
}

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.

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.

Upvotes: 1

Related Questions