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

前端 未结 14 2203
萌比男神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

    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.

提交回复
热议问题