Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning a Void object

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>{ E method(); }

class A implements B<Void>{

    public Void method(){
        // do something
        return null;
    }
}
like image 946
Robert Avatar asked Mar 09 '10 11:03

Robert


People also ask

How do I return a void?

A void function can return A void function cannot return any values. But we can use the return statement. It indicates that the function is terminated. It increases the readability of code.

Can you do return on void method?

Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.

What is a void object?

Class Void The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.


2 Answers

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

So any of the following would suffice:

  • parameterizing with Object and returning new Object() or null
  • parameterizing with Void and returning null
  • parameterizing with a NullObject of yours

You can't make this method void, and anything else returns something. Since that something is ignored, you can return anything.

like image 55
Bozho Avatar answered Sep 21 '22 22:09

Bozho


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

interface B<E>{ Optional<E> method(); }

class A implements B<Void>{

    public Optional<Void> 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.

like image 26
Erick G. Hagstrom Avatar answered Sep 24 '22 22:09

Erick G. Hagstrom