简体   繁体   English

Java相当于iif函数

[英]Java Equivalent to iif function

the question is simple, there is a functional equivalent of the famous iif in java? 问题很简单,有一个功能相当于java中着名的iif?

For example: 例如:

IIf (vData = "S", True, False)

Thanks in advance. 提前致谢。

vData.equals("S") ? true : false

或者在这种特殊情况下,显然可以写一下

vData.equals("S")

Yeah, the ternary op ? : 是的,三元运营? : ? :

vData.equals("S") ? true : false

The main difference between the Java ternary operator and IIf is that IIf evaluates both the returned value and the unreturned value, while the ternary operator short-circuits and evaluates only the value returned. 在Java三元运算符和之间的主要区别IIfIIf计算所有两个返回的值和未返回值,而三元运算短路和评估仅返回的值。 If there are side-effects to the evaluation, the two are not equivalent. 如果评估存在副作用,则两者不相同。

You can, of course, reimplement IIf as a static Java method. 当然,您可以将IIf重新实现为静态Java方法。 In that case, both parameters will be evaluated at call time, just as with IIf . 在这种情况下,两个参数将在呼叫时进行评估,就像IIf But there is no builtin Java language feature that equates exactly to IIf . 但是没有内置的Java语言功能完全等同于IIf

public static <T> T iif(boolean test, T ifTrue, T ifFalse) {
    return test ? ifTrue : ifFalse;
}

(Note that the ifTrue and ifFalse arguments must be of the same type in Java, either using the ternary operator or using this generic alternative.) (请注意, ifTrueifFalse参数在Java中必须使用相同的类型,使用三元运算符或使用此通用备选方案。)

if is the same as the logical iff. if与逻辑iff相同。

boolean result;
if (vData.equals("S"))
   result = true;
else
   result = false;

or 要么

boolean result = vData.equals("S") ? true : false;

or 要么

boolean result = vData.equals("S");

EDIT: However its quite likely you don't need a variable instead you can act on the result. 编辑:但是很可能你不需要变量而是可以对结果采取行动。 eg 例如

if (vData.equals("S")) {
   // do something
} else {
   // do something else
}

BTW it may be considered good practice to use 顺便说一句,它可能被认为是一种好的做法

 if ("S".equals(vData)) {

The difference being that is vData is null the first example will throw an exception whereas the second will be false. 不同之处在于vData为null,第一个示例将抛出异常,而第二个示例将为false。 You should ask yourself which would you prefer to happen. 你应该问问自己你希望发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM