Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Equivalent to iif function

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

For example:

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

Thanks in advance.

like image 494
seba123neo Avatar asked Jan 13 '11 20:01

seba123neo


4 Answers

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

or in this particular case obviously one could just write

vData.equals("S")
like image 152
Adrian Smith Avatar answered Nov 20 '22 01:11

Adrian Smith


Yeah, the ternary op ? :

vData.equals("S") ? true : false
like image 6
sblundy Avatar answered Nov 20 '22 02:11

sblundy


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. If there are side-effects to the evaluation, the two are not equivalent.

You can, of course, reimplement IIf as a static Java method. In that case, both parameters will be evaluated at call time, just as with IIf. But there is no builtin Java language feature that equates exactly to 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.)

like image 4
dkarp Avatar answered Nov 20 '22 01:11

dkarp


if is the same as the 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 its quite likely you don't need a variable instead you can act on the result. e.g.

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. You should ask yourself which would you prefer to happen.

like image 2
Peter Lawrey Avatar answered Nov 20 '22 01:11

Peter Lawrey