Due to the use of Generics in Java I ended up in having to implement a function having Void as return type:
public Void doSomething() { //... }
and the compiler demands that I return something. For now I’m just returning null, but I’m wondering if that is good coding practice…
I’m asking about Void, not void. The class Void, not the reserved keyword void.
I’ve also tried Void.class, void, Void.TYPE, new Void(), no return at all, but all that doesn’t work at all. (For more or less obvious reasons) (See this answer for details)
- So what am I supposed to return if the return type of a function is
Void? - What’s the general use of the
Voidclass?
Use
return null.Voidcan’t be instantiated and is merely a placeholder for theClass<T>type ofvoid.As noted above, it’s a placeholder.
Voidis what you’ll get back if you, for example, use reflection to look at a method with a return type ofvoid. (Technically, you’ll get backClass<Void>.) It has other assorted uses along these lines, like if you want to parameterize aCallable<T>.I’d say that something may be funky with your API if you needed to implement a method with this signature. Consider carefully whether there’s a better way to do what you want (perhaps you can provide more details in a different, follow-up question?). I’m a little suspicious, since this only came up ‘due to the use of generics’.