I am implementing a ResponseHandler for the apache HttpClient package, like so:
new ResponseHandler<int>() { public int handleResponse(...) { // ... code ... return 0; } } but I'd like for the handleResponse function to return nothing, i.e. void. Is this possible? The following does not compile, since void is not a valid Java type:
new ResponseHandler<void>() { public void handleResponse(...) { // ... code ... } } I suppose I could replace void with Void to return a Void object, but that's not really what I want. Question: is it possible to organize this callback situation in such a way that I can return void from handleResponse?
Alas it's not possible. You can set the code to return Void as you say, however you can never instanciate a Void so you can't actually write a function which conforms to this specification.
The void keyword specifies that a method should not have a return value.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
Type erasure is a process in which compiler replaces a generic parameter with actual class or bridge method. In type erasure, compiler ensures that no extra classes are created and there is no runtime overhead.
The Void type was created for this exact situation: to create a method with a generic return type where a subtype can be "void". Void was designed in such a way that no objects of that type can possibly be created. Thus a method of type Void will always return null (or complete abnormally), which is as close to nothing as you are going to get. You do have to put return null in the method, but this should only be a minor inconvenience.
In short: Do use Void.
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