Java 中的返回类型布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2264844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:25:50  来源:igfitidea点击:

Return Type Boolean in Java

javatypesreturn-type

提问by gmhk

I have a question on booleanreturn types. Check the following code:

我有一个关于boolean返回类型的问题。检查以下代码:

Code Sample 1

代码示例 1

boolean flag = sampleMethod();

public boolean samplemethod(){
    return false;
}

Code Sample 2

代码示例 2

sampleMethod();

public boolean samplemethod(){
    return false; 
}

In the above two examples, the code compiles properly without any compile time or run time exceptions. My doubt is, Java doesn't make it mandatory for the booleanreturn type to be assigned in the calling program, where for the other data types the program does not work. Can you please explain the reason for this to me?

在上面的两个示例中,代码正确编译,没有任何编译时或运行时异常。我的疑问是,Java 并没有强制要求boolean在调用程序中分配返回类型,而对于其他数据类型,程序不起作用。你能向我解释一下原因吗?

采纳答案by Stephen C

As @DR says, Java does not force you to assign the result of a method call. A void or non-void method call is valid as a complete statement in Java.

正如@DR 所说,Java 不会强制您分配方法调用的结果。void 或非 void 方法调用在 Java 中作为完整语句是有效的。

I would surmise that the reasons Java is designed this way include the following:

我推测 Java 以这种方式设计的原因包括以下几点:

  • Convenience: most developers would find it a nuisance if the result of every non-void method call had to be assigned.

  • Tradition: C, C++ and almost no other language force you to do this. (I have vague recollections of some language that did ... but that was long ago.)

  • Futility: you cannot stop the developer from assigning the result to a temporary variable and then ignoring it. Or writing a wrapper method that does the same thing.

  • Better alternatives: if you want to encourage the developer to pay attention to an error in Java, throw an appropriate checked exception.

  • 方便:如果必须分配每个非空方法调用的结果,大多数开发人员会觉得很麻烦。

  • 传统:C、C++ 和几乎没有其他语言强迫您这样做。(我对某些语言有模糊的回忆......但那是很久以前的事了。)

  • 徒劳:您无法阻止开发人员将结果分配给临时变量然后忽略它。或者编写一个做同样事情的包装方法。

  • 更好的选择:如果您想鼓励开发人员注意 Java 中的错误,请抛出适当的检查异常。

回答by Daniel Rikowski

Java neverforces you to assign the return value of a function call. There must be something wrong with your othercode (you might post it here, too)

Java从不强迫您分配函数调用的返回值。你的其他代码肯定有问题(你也可以在这里发布)

PS: This reminds me of good old Turbo Pascal, where you had to enable the Extended Syntax to get this behaviour.

PS:这让我想起了古老的 Turbo Pascal,你必须启用扩展语法才能获得这种行为。

回答by finnw

javaccannot issue a warning when you forget to assign the result to a variable, but FindBugscan.

javac当您忘记将结果分配给变量时无法发出警告,但FindBugs可以。

@CheckReturnValue(explanation="...")
public boolean samplemethod(){
    return false; 
}

sampleMethod(); // Now generates a warning