Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I explicitly return void from a method?

void run() {     ...     if (done) return cancel();     ... } 

where cancel() return void. This won't compile... and I can almost understand why. But if I want to return a void from a void, why not? Instead, I end up writing something like this:

if (done) {     cancel();     return; } 

I'm not looking for code style suggestions, I want to know why Java expressly prohibits this type of void return. Any info is appreciated, thanks.

like image 613
Travis Webb Avatar asked Oct 17 '11 14:10

Travis Webb


People also ask

Can you do return on 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.

Why void has no return type?

void is a type to represent nothing. That is a subtle difference : the representation is still required, even though it represents nothing. This type is used as function's return type which returns nothing. This is also used to represent generic data, when it is used as void* .

Do void function return anything in C?

Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.

What will the method return when the return type is void?

Generics. As shown above, in order to return from a method with the Void return type, we just have to return null.


2 Answers

It's an interesting question. Since java enforces a return type (void is a return type) your first statement seems to make sense. I would take this only for convention. Since void is a placeholder and not an object, it was probably decided to leave it out for language coherency or compiler simplicity.

From JLS

A return statement with no Expression must be contained in the body of a method that is declared, using the keyword void, not to return any value (§8.4), or in the body of a constructor (§8.8).

further

To be precise, a return statement with no Expression always completes abruptly, the reason being a return with no value

like image 73
Johan Sjöberg Avatar answered Oct 12 '22 00:10

Johan Sjöberg


A return statement with an expression returns the value of that expression. The type of cancel() is a void expression - it doesn't have a value.

Logically you want to execute cancel(), and then return - so that's what you have to say. The two actions (calling cancel() and then returning) are logically distinct.

Now Java could have a sort of "unit" type instead of void - but that would affect rather more than just return values.

like image 38
Jon Skeet Avatar answered Oct 11 '22 23:10

Jon Skeet