I didn't even know this was doable, but I saw while perusing some code online a method with a signature like this:
public List<Void> read( ... )
... What? Is there ever a reason to do this? What could this List
even hold? As far as I was aware, it's not possible to instantiate a Void
object.
When used as a function return type, the void keyword specifies that the function doesn't return a value. When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal."
The void keyword specifies that a method should not have a return value.
void is a type in the Java language (you can read that directly in the Java Language Specification). However the type void has no member values, that is no concrete value will ever have the type void.
void is a Java keyword. Used at method declaration and definition to specify that the method does not return any type, the method returns void .
It is possible that this method signature was created as a by-product of some generic class.
For example, SwingWorker
has two type parameters, one for final result and one for intermediate results. If you just don't want to use any intermediate results, you pass Void
as the type parameter, resulting in some methods returning Void
- i.e. nothing.
If there were a method List<V> returnAllIntermediateResults()
in SwingWorker
with Void
as the type parameter V
, it would have created a method just like you posted in your question.
The code would be perfectly valid. You can instantiate any implementation of the List
interface (e.g. ArrayList
) with type parameter Void
. But the only value a Void
type can have is null
. So the list could not hold anything else but null
s, if the implementation allows null
elements.
One case in which it may be useful is if you wanted to return a collection of return values from a function. Say
static List<T> forEach(Func<A,T> func, List<A> items) { List<T> ret = new List<T>(); for(int i = 0; i< items.length; i++) { ret.add(func.call(items[i]); } return ret; } public static void main() { ... List<Void> boringResult = forEach( new Func<Void, Integer> {@override Void call(Integer i) {...}}); }
Not that useful but you could see a case where it was required.
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