I am trying to write following code where C
is a child class of B
. And getValue method only available in C
, not in B
. But Eclipse is showing an error in this statement:
Optional.ofNullable(A).map(A::getB).map(C::getValue);
If it is normal case, we will type cast and write like ((C)a.getB()).getValue()
. How do I write same in terms of an Optional
?
You can add map(C.class::cast)
into your chain.
Optional.ofNullable(aOrNull).map(A::getB).map(C.class::cast).map(C::getValue);
You could also combine some of your chain of maps.
If getB()
never returns null, you could just have:
Optional.ofNullable(aOrNull).map(a -> ((C) a.getB()).getValue());
To retain the null-avoiding behaviour of the Optional
if getB()
returns null, you could have:
Optional.ofNullable(aOrNull).map(A::getB).map(b -> ((C) b).getValue());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With