Optionally getting field

后端 未结 2 1720
执念已碎
执念已碎 2020-12-11 03:46

I have a class structure like this:

public class Foo {
    private FooB foob;

    public Optional getFoob() {
        return Optional.ofNullable         


        
相关标签:
2条回答
  • 2020-12-11 04:18

    Why you dont add a getValue methode to the class Foo? This would be a kind of delegation.

    public class Foo {
       ...
       public Integer getValue() {
           if (foob == null) {
              return null;
           }
           return foob.getValA();
       }
    }
    
    0 讨论(0)
  • 2020-12-11 04:19

    What you are describing is the method Optional.map:

    Integer valA = foo.getFoob().map(foo -> foo.getValA()).orElse(null);
    

    map lets you transform the value inside an Optional with a function if the value is present, and returns an empty the optional if the value in not present.

    Note also that you can return null from the mapping function, in which case the result will be Optional.empty().

    0 讨论(0)
提交回复
热议问题