The Elvis Operator

Elvis 运算符是三元运算符语法的缩写,用于 Groovy 语言中。使用三元运算符语法,您通常必须重复变量两次,如下例所示:

The Elvis operator is a shortening of the ternary operator syntax and is used in the Groovy language. With the ternary operator syntax, you usually have to repeat a variable twice, as the following example shows:

String name = "Elvis Presley";
String displayName = (name != null ? name : "Unknown");

相反,可以使用 Elvis 操作符(以其对 Elvis 发型相似性的命名而来)。以下示例展示了如何使用 Elvis 操作符:

Instead, you can use the Elvis operator (named for the resemblance to Elvis' hair style). The following example shows how to use the Elvis operator:

  • Java

  • Kotlin

ExpressionParser parser = new SpelExpressionParser();

String name = parser.parseExpression("name?:'Unknown'").getValue(new Inventor(), String.class);
System.out.println(name);  // 'Unknown'
val parser = SpelExpressionParser()

val name = parser.parseExpression("name?:'Unknown'").getValue(Inventor(), String::class.java)
println(name)  // 'Unknown'

SpEL Elvis 运算符除了 null 对象外还检查 empty 字符串。因此原始代码段仅仅接近模拟运算符的语义(它需要一个附加的 !name.isEmpty() 检查)。

The SpEL Elvis operator also checks for empty Strings in addition to null objects. The original snippet is thus only close to emulating the semantics of the operator (it would need an additional !name.isEmpty() check).

以下清单展示了更复杂的示例:

The following listing shows a more complex example:

  • Java

  • Kotlin

ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();

Inventor tesla = new Inventor("Nikola Tesla", "Serbian");
String name = parser.parseExpression("name?:'Elvis Presley'").getValue(context, tesla, String.class);
System.out.println(name);  // Nikola Tesla

tesla.setName("");
name = parser.parseExpression("name?:'Elvis Presley'").getValue(context, tesla, String.class);
System.out.println(name);  // Elvis Presley
val parser = SpelExpressionParser()
val context = SimpleEvaluationContext.forReadOnlyDataBinding().build()

val tesla = Inventor("Nikola Tesla", "Serbian")
var name = parser.parseExpression("name?:'Elvis Presley'").getValue(context, tesla, String::class.java)
println(name)  // Nikola Tesla

tesla.setName("")
name = parser.parseExpression("name?:'Elvis Presley'").getValue(context, tesla, String::class.java)
println(name)  // Elvis Presley

可以在表达式中使用 Elvis 操作符来应用默认值。以下示例展示了如何在 @Value 表达式中使用 Elvis 操作符:

You can use the Elvis operator to apply default values in expressions. The following example shows how to use the Elvis operator in a @Value expression:

@Value("#{systemProperties['pop3.port'] ?: 25}")

如果定义了系统属性 pop3.port,则会注入该属性,否则注入 25。

This will inject a system property pop3.port if it is defined or 25 if not.