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

前端 未结 14 2208
萌比男神i
萌比男神i 2021-01-01 08:23
void run() {
    ...
    if (done) return cancel();
    ...
}

where cancel() return void. This won\'t compile... and I ca

相关标签:
14条回答
  • 2021-01-01 09:14

    Void is not a real type. Void is just a place holder to make syntax of methods definition more consistent. This is not the java innovation; this is inherited from C.

    This is the reason that compiler does not allow you to write return cancel() even if method cancel() is void.

    0 讨论(0)
  • 2021-01-01 09:14

    The Java grammar actually doesn't care about the type of a method call, so that's not the issue. It has to be something farther down the chain, in the type-checking system. I think the bottom line is that if a grammatically optional statement is included after the return keyword, then the system expects a value to pass on. void certainly is a type, but there are no values with type void.

    But, of course, none of this really explains the answer to your question. As you pointed out, there's no reason why this idiom should not be allowed. But there's also no valid reason to allow it. So it's a toss up. One could try to rationalize why they did what they did, but that would probably be pointless.

    0 讨论(0)
提交回复
热议问题