Java 的三元/条件运算符 (?:) 可以用于调用方法而不是赋值吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12554547/
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-10-31 09:20:36  来源:igfitidea点击:

Can Java's ternary/conditional operator (?:) be used to call methods instead of assigning values?

javaconditional-operator

提问by Voldemort

In pages like http://en.wikipedia.org/wiki/?:the ternary/conditional operator ?:seems to be used for conditional assignments. I tried to use it for method calling, like this:

在像http://en.wikipedia.org/wiki/? 这样的页面中三元/条件运算符?:似乎用于条件赋值。我尝试将它用于方法调用,如下所示:

(condition) ? doThis() : doThat();

Both methods return void. Java tells me it is not a statement.

这两种方法都返回void。Java 告诉我这不是声明。

So, I'm guessing I can't do conditional method calling... or can I?

所以,我猜我不能做条件方法调用......或者我可以吗?

采纳答案by Jodaka

Think of ternary operators like a method in this case. Saying a ? b : cis (for the intents and purposes you're considering, see lasseespeholt's comment) equivalent to calling the pseudocode method:

在这种情况下,将三元运算符视为一种方法。说a ? b : c是(对于您正在考虑的意图和目的,请参阅 lasseespeholt 的评论)相当于调用伪代码方法:

ternary(a, b, c)
    if a
        return b
    else
        return c

which is why people can say things like x = a ? b : c; it's basically like saying x = ternary(a, b, c). When you say (condition) ? doThis() : doThat(), you're in effect saying:

这就是为什么人们可以说这样的话x = a ? b : c;基本上就像说x = ternary(a, b, c)。当你说 时(condition) ? doThis() : doThat(),你实际上是在说:

if condition
    return doThis()
else
    return doThat()

Look what happens if we try to substitute the methods for what they return

看看如果我们尝试用方法替换它们返回的内容会发生什么

 if condition
    return ???
 else
    return ???

It doesn't even make sense to consider it. doThis()and doThat()don't return anything, because voidisn't an instantiable type, so the ternarymethod can't return anything either, so Java doesn't know what to do with your statement and complains.

考虑它甚至没有意义。 doThis()并且doThat()不返回任何内容,因为void它不是可实例化的类型,因此该ternary方法也不能返回任何内容,因此 Java 不知道如何处理您的语句并抱怨。

There are ways around this, but they're all bad practice (you could modify your methods to have a return value but don't do anything with what they return, you could create new methods that call your methods and then return null, etc.). You're much better off just using an ifstatement in this case.

有办法解决这个问题,但它们都是不好的做法(您可以修改您的方法以获得返回值,但不要对它们返回的内容做任何事情,您可以创建调用您的方法然后返回 null 的新方法,等等.) if在这种情况下,您最好只使用语句。

EDITFurthermore, there's an even bigger issue. Even if you were returning values, Java does not consider a ? b : ca statement in any sense.

编辑此外,还有一个更大的问题。即使您正在返回值,Java 也不考虑a ? b : c任何意义上的语句。

回答by neXus

The ternary operator is simply syntactic sugar.
It makes code easier to read/write, but it does not add real functionality.
Its primary use was to compress several lines of code into a single line, and was very useful when building Strings that differ only slightly, based on some conditions.

三元运算符只是语法糖
它使代码更易于读/写,但它没有添加真正的功能。
它的主要用途是将多行代码压缩为一行,在构建基于某些条件仅略有不同的字符串时非常有用。

eg.

例如。

Collection<?> col = ...
System.out.println("There " + (col.size()==1 ? "is" : "are") + " "
     + col.size() + " " + (col.size()==1 ? "element" : "elements")
     + " in the collection");

instead of

代替

Collection<?> col = ...
String message = "There ";
if(col.size()==1)
    message += "is";
else
    message += "are";
message += " "+col.size()
if(col.size()==1)
    message += " element";
else
    message += " elements";
message += " in the collection";
System.out.println(message);

As you can see, it simplifies the code.
(note: In the second example it is better to use StringBuilderinstead of String concatenation)

如您所见,它简化了代码。
(注意:在第二个例子中最好使用StringBuilder而不是字符串连接)

But since (condition) ? doThis() : doThat();(without return values) has the same meaning as if(condition) doThis(); else doThat();there would be two ways of writing the same thing, without adding functionality. It would only complicate things:

但是因为(condition) ? doThis() : doThat();(没有返回值)具有相同的含义,因为if(condition) doThis(); else doThat();在不添加功能的情况下有两种编写相同内容的方法。它只会使事情复杂化:

  • for programmers: code is not uniform
  • for the implementation of the ternary operator: it now has to also support voidmethods
  • 对于程序员:代码不统一
  • 对于三元运算符的实现:它现在还必须支持void方法


So No, the ternary operation can not be used for conditional method calling. Use if-else instead:

所以,三元运算不能用于条件方法调用。改用 if-else:

if(condition)
    doThis();
else
    doThat(); 

回答by J.A.I.L.

The ternary (conditional) operator returns a value. If your methods don't, they can't be used as parts of the operator (where it takes the value).

三元(条件)运算符返回一个值。如果您的方法不这样做,则它们不能用作运算符的一部分(它接受值的地方)。

In order to understand it better, let's think of one simple binary operator: +. It works this way:

为了更好地理解它,让我们考虑一个简单的二元运算符:+. 它是这样工作的:

<eval1> + <eval2>  -->  <value>

It needs of 2 evaluable parts, and returns another. If you typed

它需要 2 个可评估的部分,并返回另一个。如果你输入

doThis() + doThat();

or even

甚至

gimmeAValue = doThis() + doThat();

it would fail, as neither doThis()nor doThat()evaluate to anything (they "return" void). Of course, both <eval1>and <eval2>must be of some "compatible" type in order the +operator can handle them and return a value of some type.

它会失败,因为既不doThis()也不doThat()评估任何东西(它们“返回” void)。当然,无论是<eval1><eval2>必须是为了在某些“兼容”式的+操作员可以处理它们并返回某种类型的值。

Now let's see the ternary operator:

现在让我们看看三元运算符:

<evalBoolean> ? <eval1> : <eval2>  -->  <value>

It takes 3 evaluable parts, and returns a value.

它需要 3 个可评估的部分,并返回一个值。

The first evaluable part must be understandable (castable) by the compiler as a boolean. It will be used to decide which of the other 2 evaluable parts has to be returned.

第一个可评估的部分必须可以被编译器理解(可转换)为布尔值。它将用于决定必须退回其他 2 个可评估部件中的哪一个。

The other two evaluable parts must be, well... evaluable. To something. Of some type.

其他两个可评估的部分必须是……可评估的。对某事。某种类型的。

In other words: the ternary conditional operator is intended to return something, not as code branching. Used this way:

换句话说:三元条件运算符旨在返回某些内容,而不是作为代码分支。用这种方式:

gimmeAValue = testMe() ? returnThis() : returnThat();