Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Map typecasting to child class object

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?

like image 216
Sandeep Avatar asked Jan 29 '23 11:01

Sandeep


1 Answers

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());
like image 184
khelwood Avatar answered Feb 02 '23 12:02

khelwood