Passing Optional.absent() values to methods concisely

后端 未结 3 1243
不思量自难忘°
不思量自难忘° 2021-02-18 22:31

One problem with using Guava\'s Optional type as arguments of methods is that you can\'t simply write

// method declaration
public void foo(Optional         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-18 22:57

    If you are dealing with a small set of Optional<> types (e.g., mostly strings or a handful of other types), just create some helper methods that bind the type argument for you:

    public final class AbsentValues {
        public static Optional absentString() {
            return Optional.absent();
        }
    }
    

    You can even import these statically to result in cleaner code:

    import static AbsentValues.*;
    
    ...
    
    foo(absentString());
    

    For less common Optional<> types, just specify the type argument explicitly. It may not be pretty, but it's correct.

提交回复
热议问题