Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do I return if the return type of a method is Void? (Not void!)

People also ask

What is the return type of a 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.

Which of the return type is not void?

In our function declaration after the parentheses and colon we see the word number, which is the return type. Another clue that this is a non-void function is that in the body, the statement return 110; means that this function will return the number value 110. Void functions will not include a return statement.

What does a non-void method return?

The way that a non-void method is called differs from the way that a void method is called in that the call is made from within other Java statements. Since a non-void method always returns a value, this value has to be stored in a variable, printed, or returned to a Java control structure or another method.

Can we return null for void method?

In a large variety of languages void as return type is used to indicate that a function doesn't return anything. Dart allows returning null in functions with void return type but it also allow using return; without specifying any value. To have a consistent way you should not return null and only use an empty return.


So what am I supposed to return if the return type of a function has to be Void?

Use return null. Void can't be instantiated and is merely a placeholder for the Class<T> type of void.

What's the point of Void?

As noted above, it's a placeholder. Void is what you'll get back if you, for example, use reflection to look at a method with a return type of void. (Technically, you'll get back Class<Void>.) It has other assorted uses along these lines, like if you want to parameterize a Callable<T>.

Due to the use of generics in Java I ended up in having to implement this function

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".


There's no way to instantiate a Void, so the only thing you can return is null.


return null is the way to go.


To make clear why the other suggestions you gave don't work:

Void.class and Void.TYPE point to the same object and are of type Class<Void>, not of Void.

That is why you can't return those values. new Void() would be of type Void but that constructor doesn't exist. In fact, Void has no public constructors and so cannot be instantiated: You can never have any object of type Void except for the polymorphic null.

Hope this helps! :-)