0

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,

yanana
  • 2,241
  • 2
  • 18
  • 28
user3097712
  • 1,565
  • 6
  • 27
  • 49
  • 4
    Just call the `get()` on the `Optional`, i.e `a.getName().get()`. How you deal with the `null`s is up to you (see [`ifPresent`](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#isPresent--)). Read more about the `Optional` [here](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#get--). – mystarrocks Jul 20 '15 at 23:53
  • wow, thanks for that. I did not know that. The only thing what I tried was to cast it, so (String)a.getName() but I did not work because you can not cast from Optional to String. The advice with the additional get() helps. Thank you ! – user3097712 Jul 21 '15 at 00:07
  • You're going from `String name` to `Optional name`, so not only change the constructor (or better yet make another), you'll have to change the variable type from `String` to `Optional`. – CoderMusgrove Jul 21 '15 at 01:05

2 Answers2

1

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.

dimo414
  • 47,227
  • 18
  • 148
  • 244
0

You could make another constructor that takes aan Optional.

Zymus
  • 1,673
  • 1
  • 18
  • 38