void 方法不能返回 void 方法的值? [英] Void methods can't return the value of a void method?
问题描述
我不介意我不明白,但我想知道为什么会这样:
I don't mind if I don't understand, but I want to know why this happens:
void something(String a) {
return hi();
}
void hi() {
return;
}
这里奇怪的是,hi()
也有一个 void
的返回类型.我的 IDE 中出现语法错误:
The odd thing here, is that hi()
also has a return type of void
. I get the syntax error in my IDE:
Void methods cannot return a value
此外,代码无法编译:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Void methods cannot return a value
at Resources.setSystemProperties(Resources.java:33)
at Resources.main(Resources.java:49)
我希望这会发生:
hi() -> return nothing
return [nothing] -> hi() is nothing
所以最后,它什么都不返回,就像 void
方法应该的那样.
So in the end, it returns nothing, just like a void
method should.
为什么会发生这种行为?为什么在返回 void 方法的结果时代码不编译?
Why does this behaviour happen? And why doesn't the code compile, when return the result of a void method?
推荐答案
这在 JLS 14.17:
带有表达式的 return 语句必须包含在以下之一中,否则会发生编译时错误:
A return statement with an Expression must be contained in one of the following, or a compile-time error occurs:
- 声明返回值的方法
- 一个 lambda 表达式
void
方法未声明为返回值,因此在此类方法中不能出现带有表达式的 return 语句(如函数调用).
A void
method is not declared to return a value, so a return statement with an expression (like a function call) cannot happen in such a method.
此外,由于 JLS 15.12.3:
Additionally, you can't return the result of a void
method due to this language in JLS 15.12.3:
如果编译时声明是 void
,则方法调用必须是顶级表达式(即表达式语句中的 Expression 或 <for
语句的 em>ForInit 或 ForUpdate 部分),或者发生编译时错误.
If the compile-time declaration is
void
, then the method invocation must be a top level expression (that is, the Expression in an expression statement or in the ForInit or ForUpdate part of afor
statement), or a compile-time error occurs.
换句话说,由于 a.notify()
是 void
,你可以在它看起来像一个语句的上下文中使用它(即,单独在一行上)) 但不是在它看起来像一个表达式的上下文中(即,你不能将它的值分配给一个变量,返回它等).
In other words, since a.notify()
is void
, you can use it in contexts where it looks like a statement (ie, all alone on a line) but not in contexts where it looks like an expression (ie, you can't assign its value to a variable, return it, etc).
这篇关于void 方法不能返回 void 方法的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!