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

前端 未结 14 2316
萌比男神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条回答
  •  -上瘾入骨i
    2021-01-01 08:49

    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 (calling cancel() 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.

提交回复
热议问题