4.3.13 삼항 연산자 (If-Then-Else) by ks

표현식에서 조건 로직 if-then-else를 사용해서 삼항연산을 할 수 있다. 아래는 그에 대한 최소 예제이다.

String falseString = parser.parseExpression(
        "false ? 'trueExp' : 'falseExp'").getValue(String.class);

이 경우에 boolean은 false 결과가 falsExp로 반환된다.더 현실적인 예제는 다음과 같다.

parser.parseExpression("Name").setValue(societyContext, "IEEE");
societyContext.setVariable("queryName", "Nikola Tesla");

expression = "isMember(#queryName)? #queryName + ' is a member of the ' " +
        "+ Name + ' Society' : #queryName + ' is not a member of the ' + Name + ' Society'";

String queryResultString = parser.parseExpression(expression)
        .getValue(societyContext, String.class);
// queryResultString = "Nikola Tesla is a member of the IEEE Society"

다음 섹션을 보면 Elvis 연산자로 삼항연산을 더 짧은 신택스로 할 수 있다.

Last updated