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

前端 未结 14 2207
萌比男神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 08:55

    return x explicitly means "return the value x", regardless of what that type is (the type, of course, still has to match the return type of whatever function that statement is placed in).

    void is, strictly speaking, the absence of a type, and by extension, the absence of a value - so it does not make sense to return one, just like it does not make sense (and is not allowed) to declare a void variable.

    0 讨论(0)
  • 2021-01-01 08:58

    It's a tautology. Meaning, void defines that the method has no return value. Therefore, how can you "return void" when void is no return at all?

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

    From the 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, or in the body of a constructor

    ...

    A return statement with an Expression must be contained in a method declaration that is declared to return a value or a compile-time error occurs. The Expression must denote a variable or value of some type T, or a compile-time error occurs. The type T must be assignable to the declared result type of the method, or a compile-time error occurs.

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

    Because you don't return void. void is not a value, so it can't be returned.

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

    void is not a type. void in the method definition is just a placeholder for returns nothing.

    0 讨论(0)
  • 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

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