为什么我不能从方法中显式返回void? [英] Why can't I explicitly return void from a method?

查看:134
本文介绍了为什么我不能从方法中显式返回void?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void run() {
    ...
    if (done) return cancel();
    ...
}

其中取消( ) return void 。这不会编译......我可以几乎理解为什么。但是如果我想从虚空中归还一个空洞,为什么不呢?相反,我最终写了这样的东西:

where cancel() return void. This won't compile... and I can almost understand why. But if I want to return a void from a void, why not? Instead, I end up writing something like this:

if (done) {
    cancel();
    return;
}

我不是在寻找代码风格的建议,我想知道为什么选择Java明确禁止此类无效回报。感谢任何信息。

I'm not looking for code style suggestions, I want to know why Java expressly prohibits this type of void return. Any info is appreciated, thanks.

推荐答案

带有表达式的return语句返回该表达式的值。 cancel()的类型是一个void表达式 - 它没有值。

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.

逻辑上你要执行 cancel(),然后返回 - 这就是你要说的。这两个动作(调用 cancel()然后返回)在逻辑上是不同的。

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.

现在Java 可以有一种单位类型而不是 void - 但这不仅会影响返回值。

Now Java could have a sort of "unit" type instead of void - but that would affect rather more than just return values.

这篇关于为什么我不能从方法中显式返回void?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆