2
2
= The Elvis Operator
3
3
4
4
The 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:
8
8
9
- [source,groovy ,indent=0,subs="verbatim,quotes"]
9
+ [source,java ,indent=0,subs="verbatim,quotes"]
10
10
----
11
11
String name = "Elvis Presley";
12
12
String displayName = (name != null ? name : "Unknown");
13
13
----
14
14
15
15
Instead, 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 :
17
17
18
18
[tabs]
19
19
======
@@ -38,9 +38,13 @@ Kotlin::
38
38
----
39
39
======
40
40
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
+ ====
44
48
45
49
The following listing shows a more complex example:
46
50
@@ -79,7 +83,7 @@ Kotlin::
79
83
----
80
84
======
81
85
82
- [NOTE ]
86
+ [TIP ]
83
87
=====
84
88
You can use the Elvis operator to apply default values in expressions. The following
85
89
example 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:
89
93
@Value("#{systemProperties['pop3.port'] ?: 25}")
90
94
----
91
95
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.
93
98
=====
94
-
95
-
0 commit comments