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

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

    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

提交回复
热议问题