Improve documentation for SpEL Elvis operator

This commit is contained in:
Sam Brannen 2025-03-12 13:01:27 +01:00
parent f8a82b46c1
commit d3d951e44b
1 changed files with 15 additions and 12 deletions

View File

@ -2,18 +2,18 @@
= The Elvis Operator = The Elvis Operator
The Elvis operator is a shortening of the ternary operator syntax and is used in the The Elvis operator is a shortening of the ternary operator syntax and is used in the
https://www.groovy-lang.org/operators.html#_elvis_operator[Groovy] language. https://www.groovy-lang.org/operators.html#_elvis_operator[Groovy] language. With the
With the ternary operator syntax, you usually have to repeat a variable twice, as the ternary operator syntax, you often have to repeat a variable twice, as the following
following example shows: Java example shows:
[source,groovy,indent=0,subs="verbatim,quotes"] [source,java,indent=0,subs="verbatim,quotes"]
---- ----
String name = "Elvis Presley"; String name = "Elvis Presley";
String displayName = (name != null ? name : "Unknown"); String displayName = (name != null ? name : "Unknown");
---- ----
Instead, you can use the Elvis operator (named for the resemblance to Elvis' hair style). 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: The following example shows how to use the Elvis operator in a SpEL expression:
[tabs] [tabs]
====== ======
@ -38,9 +38,13 @@ Kotlin::
---- ----
====== ======
NOTE: The SpEL Elvis operator also checks for _empty_ Strings in addition to `null` objects. [NOTE]
The original snippet is thus only close to emulating the semantics of the operator (it would need an ====
additional `!name.isEmpty()` check). The SpEL Elvis operator also treats an _empty_ String like a `null` object. Thus, the
original Java example is only close to emulating the semantics of the operator: it would
need to use `name != null && !name.isEmpty()` as the predicate to be compatible with the
semantics of the SpEL Elvis operator.
====
The following listing shows a more complex example: The following listing shows a more complex example:
@ -79,7 +83,7 @@ Kotlin::
---- ----
====== ======
[NOTE] [TIP]
===== =====
You can use the Elvis operator to apply default values in expressions. The following 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: 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:
@Value("#{systemProperties['pop3.port'] ?: 25}") @Value("#{systemProperties['pop3.port'] ?: 25}")
---- ----
This will inject a system property `pop3.port` if it is defined or 25 if not. This will inject the value of the system property named `pop3.port` if it is defined or
`25` if the property is not defined.
===== =====