Consider the below interfaces:
public interface Vc{
}
public interface Vd< P extends Vc, C extends Vcc<{
...
}
public interface VcResult extends Vc{
}
There exists a method which returns Optional
public Optional<Vc> getData()
Here is the method where I am trying to improve the code:
public VcResult mainMethod(){
Optional<Vc> vc = getData();
if(vc.isEmpty){
return anotherMethod();
}
return (VcResult)vc.get();
}
Please suggest in converting this portion:
if(vc.isEmpty){
return anotherMethod();
}
return (VcResult)vc.get();
to this:
vc.map()..orElseGet(() -> anotherMethod());
What will be the argument of map in the above statement.
>Solution :
You can use VcResult‘s class object to cast it:
public VcResult mainMethod(){
return getData().map(VcResult.class::cast).orElseGet(this::anotherMethod);
}