returning a Void object

前端 未结 5 1273
故里飘歌
故里飘歌 2020-12-09 00:17

What is the correct way to return a Void type, when it isn\'t a primitive? Eg. I currently use null as below.

interface B{ E method();          


        
5条回答
  •  旧时难觅i
    2020-12-09 01:11

    Java 8 has introduced a new class, Optional, that can be used in such cases. To use it, you'd modify your code slightly as follows:

    interface B{ Optional method(); }
    
    class A implements B{
    
        public Optional method(){
            // do something
            return Optional.empty();
        }
    }
    

    This allows you to ensure that you always get a non-null return value from your method, even when there isn't anything to return. That's especially powerful when used in conjunction with tools that detect when null can or can't be returned, e.g. the Eclipse @NonNull and @Nullable annotations.

提交回复
热议问题