Reputation: 1462
I have a code:
public interface A{
default Optional<MyClass> getMyClass() {
return Optional.empty();
}
default boolean isPresent(){
return getMyClass().isPresent();
}
}
public enum MyEnum implements A{
private MyClass someObject;
MyEnum(MyClass someObject) {
this.someObject = someObject;
}
//...
@Override
public Optional<MyClass> getMyClass() {
return Optional.ofNullable(someObject);
}
}
I would like to change this code into something like Optional.ifPresent()
. I need this instead of Optional.isPresent
+ Optional.get
which I have now.
I tried to do something like Optional.ofNullable(someObject).ifPresent()
but I have no idea what should be placed in ifPresent()
parameter to get same result as from above code.
EDIT:
From comments I understood that a solution is to change
if(something.isPresent()){ //do something }
to
something.getMyClass().ifPresent(val -> //do something);
in class where I use interface.
Upvotes: 1
Views: 1264
Reputation: 2286
allocer,
Case 1
if(something.isPresent())
{
//do something
}
In this block you can work with not final variables, for example:
String myString = null;
if(something.isPresent())
{
myString = "Hello";
}
Case 2
something.getMyClass().ifPresent(val -> //do something);
In this block you cannot work with not final variables, for example:
String myString = null;
something.getMyClass().ifPresent(val -> myString = "Hello"); // does not work
to fix it you need to use one element list:
final String myString[] = {""};
something.getMyClass().ifPresent(val -> myString[0] = "Hello"); // will work
If you have final object then you can invoke its methods to modify it:
final SomeClass object = new SomeClass();
something.getMyClass().ifPresent(val -> object.someMethod()); // will work
Also you can use method references:
class SomeClass {
// ...
public void calculate(MyClass value) {
// do something
}
public void someMethod() {
something.getMyClass().ifPresent(this::calculate);
}
}
Upvotes: 1