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.
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 (callingcancel()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.