我不介意我不明白,但我想知道为什么会这样:
void something(String a) {
return hi();
}
void hi() {
return;
}
奇怪的是,hi()的返回类型void。 我在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方法一样。
为什么会出现这种情况? 当返回void方法的结果时,为什么代码不能编译?
答案:void方法无法返回值。 就如此容易。
并且a.notify()是void ...那么为什么我不能返回结果呢? 我有三个答案,但似乎没有人试图真正回答我的问题
return ;和return;之间存在差异。 我想这就是令你困惑的事情。
看看Scala,它有点像你在这里想做的那样。 Java没有。
@SotiriosDelimanolis我想OP对我上次评论感到困惑
这在JLS 14.17中定义:
A return statement with an Expression must be contained in one of the following, or a compile-time error occurs:
A method that is declared to return a value
A lambda expression
未声明void方法返回值,因此在这样的方法中不能发生带有表达式的return语句(如函数调用)。
此外,由于JLS 15.12.3中的此语言,您无法返回void方法的结果:
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 a for statement), or a compile-time error occurs.
换句话说,因为a.notify()是void,你可以在它看起来像一个语句的上下文中使用它(即,所有单独在一行上),但不能在它看起来像表达式的上下文中使用它(即,你可以' t将其值赋给变量,返回它等。
我发誓,所有这些答案......这个实际上让我有点理解这种行为。 谢谢。
因为这就是语言的运作方式。您不能使用return关键字在返回类型为void的方法中返回值。 void不是可以传递的实际值:
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.
这是James Iry的一篇文章,将Java中的void与Scala中的Unit进行比较。 (与void不同,unit是可以返回的实际值。)他演示了使用Unit类型而不是void的优点:
Java, C++, and C# programmers do solve this problem all the time. One common option is to not use Function but some other concept like"Action" to mean a function that takes a string, performs a side effect, and returns nothing useful. Then you essentially duplicate"map" into something called perhaps"foreach" that expects an Action and returns void. That probably makes sense in this case since a list of references to a meaningless value is perhaps silly, but it also means a great deal of code duplication if this kind of higher order programming is common. For instance, you can't write just one compose function that creates a function from two other functions, you also have to write a compose that takes an action and a function to create an action.
@Codebender:对,修好了。
a.notify()只是用作void方法的一个例子,仅仅因为我想不出任何其他方法。
@Zizouz212:明白了,这只是一个非常糟糕的例子。 你可以使用返回类型为void的另一个方法。
当然,在那种情况下,我会这样做。
声明为void的函数不能return任何东西,就像错误所说的那样。你假设a.notify()返回任何东西都是假的,因为a.notify()也不能返回任何东西(因为它是无效的)。
a.notify()是void方法。 我从来没有说它会返回任何东西。
return statements simply cannot be used with `Void` as it's Return type.
你无法改变语言规则!
Java编译器不会那么深入。当它在void函数中看到返回关键字后面带有一些值时会抛出编译错误。这是编程的。就如此容易。
我可以将简单的return;放在我的代码中......没有错误