可以使用Java的三元/条件运算符(?:)来调用方法而不是赋值吗? [英] Can Java's ternary/conditional operator (?:) be used to call methods instead of assigning values?

查看:396
本文介绍了可以使用Java的三元/条件运算符(?:)来调用方法而不是赋值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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

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

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

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

推荐答案

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

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

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

这就是为什么人们会说 x = a? b:c ;它基本上就像说 x =三元(a,b,c)。当你说(条件)? doThis():doThat(),你实际上说:

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:

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 ???

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

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

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

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 if statement in this case.

EDIT 此外,还有一个更大的问题。即使您返回值,Java也不会考虑 a? b:c 任何意义上的陈述。

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

这篇关于可以使用Java的三元/条件运算符(?:)来调用方法而不是赋值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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