void run() {
...
if (done) return cancel();
...
}
where cancel()
return void
. This won\'t compile... and I ca
return x
explicitly means "return the value x", regardless of what that type is (the type, of course, still has to match the return type of whatever function that statement is placed in).
void
is, strictly speaking, the absence of a type, and by extension, the absence of a value - so it does not make sense to return one, just like it does not make sense (and is not allowed) to declare a void
variable.
It's a tautology. Meaning, void defines that the method has no return value. Therefore, how can you "return void" when void is no return at all?
From the 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, or in the body of a constructor
...
A return statement with an Expression must be contained in a method declaration that is declared to return a value or a compile-time error occurs. The Expression must denote a variable or value of some type T, or a compile-time error occurs. The type T must be assignable to the declared result type of the method, or a compile-time error occurs.
Because you don't return void
. void
is not a value, so it can't be returned.
void
is not a type. void
in the method definition is just a placeholder for returns nothing.
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