三元運算子 (If-Then-Else)

您可以在表示式內部使用三元運算子執行 if-then-else 條件邏輯。以下清單顯示了一個最小示例

  • Java

  • Kotlin

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

在這種情況下,布林值 false 會返回字串值 'falseExp'。一個更真實的示例如下

  • Java

  • Kotlin

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"
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'"

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

請參閱關於 Elvis 運算子的下一節,瞭解三元運算子更簡潔的語法。

© . This site is unofficial and not affiliated with VMware.