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;
}
}
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.
Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.
Class Void The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.
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:
Object
and returning new Object()
or null
Void
and returning null
NullObject
of yoursYou can't make this method void
, and anything else returns something. Since that something is ignored, you can return anything.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With