22= The Elvis Operator
33
44The Elvis operator is a shortening of the ternary operator syntax and is used in the
5- https://www.groovy-lang.org/operators.html#_elvis_operator[Groovy] language.
6- With the ternary operator syntax, you usually have to repeat a variable twice, as the
7- following example shows:
5+ https://www.groovy-lang.org/operators.html#_elvis_operator[Groovy] language. With the
6+ ternary operator syntax, you often have to repeat a variable twice, as the following
7+ Java example shows:
88
9- [source,groovy ,indent=0,subs="verbatim,quotes"]
9+ [source,java ,indent=0,subs="verbatim,quotes"]
1010----
1111 String name = "Elvis Presley";
1212 String displayName = (name != null ? name : "Unknown");
1313----
1414
1515Instead, you can use the Elvis operator (named for the resemblance to Elvis' hair style).
16- The following example shows how to use the Elvis operator:
16+ The following example shows how to use the Elvis operator in a SpEL expression :
1717
1818[tabs]
1919======
@@ -38,9 +38,13 @@ Kotlin::
3838----
3939======
4040
41- NOTE: The SpEL Elvis operator also checks for _empty_ Strings in addition to `null` objects.
42- The original snippet is thus only close to emulating the semantics of the operator (it would need an
43- additional `!name.isEmpty()` check).
41+ [NOTE]
42+ ====
43+ The SpEL Elvis operator also treats an _empty_ String like a `null` object. Thus, the
44+ original Java example is only close to emulating the semantics of the operator: it would
45+ need to use `name != null && !name.isEmpty()` as the predicate to be compatible with the
46+ semantics of the SpEL Elvis operator.
47+ ====
4448
4549The following listing shows a more complex example:
4650
@@ -79,7 +83,7 @@ Kotlin::
7983----
8084======
8185
82- [NOTE ]
86+ [TIP ]
8387=====
8488You can use the Elvis operator to apply default values in expressions. The following
8589example shows how to use the Elvis operator in a `@Value` expression:
@@ -89,7 +93,6 @@ example shows how to use the Elvis operator in a `@Value` expression:
8993 @Value("#{systemProperties['pop3.port'] ?: 25}")
9094----
9195
92- This will inject a system property `pop3.port` if it is defined or 25 if not.
96+ This will inject the value of the system property named `pop3.port` if it is defined or
97+ `25` if the property is not defined.
9398=====
94-
95-
0 commit comments