Java Equivalent to iif Function

the question is simple, is there a functional equivalent of the famous iif in java?

For example:

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

Thanks in advance.

+8
java function if-statement equivalent iif-function
source share
4 answers
 vData.equals("S") ? true : false 

or in this particular case, obviously, you could just write

 vData.equals("S") 
+20
source share

Yes triple op ? : ? :

 vData.equals("S") ? true : false 
+5
source share

The main difference between the Java triple operator and IIf is that IIf evaluates both the return value and the non-return value, while the triple operator closes and evaluates only the return IIf there are side effects to the evaluation, they are not equivalent.

Of course, you can override IIf as a static Java method. In this case, both parameters will be evaluated during the conversation, as in IIf . But there is no Java language built-in function that is exactly equal to IIf .

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

(Note that the ifTrue and ifFalse must be of the same type in Java, either using the ternary operator or using this general alternative.)

+3
source share

if matches logical 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, most likely, you do not need a variable, instead you can influence the result. eg.

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

BTW can be considered good practice to use

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

The difference is that vData is null, the first example will throw an exception, while the second will be false. You must ask yourself what you would rather do.

+2
source share

Source: https://habr.com/ru/post/651044/


All Articles