Browse Source

Improve documentation for SpEL Elvis operator

pull/34585/head
Sam Brannen 1 year ago
parent
commit
d3d951e44b
  1. 27
      framework-docs/modules/ROOT/pages/core/expressions/language-ref/operator-elvis.adoc

27
framework-docs/modules/ROOT/pages/core/expressions/language-ref/operator-elvis.adoc

@ -2,18 +2,18 @@ @@ -2,18 +2,18 @@
= The Elvis Operator
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.
With the ternary operator syntax, you usually have to repeat a variable twice, as the
following example shows:
https://www.groovy-lang.org/operators.html#_elvis_operator[Groovy] language. With the
ternary operator syntax, you often have to repeat a variable twice, as the following
Java example shows:
[source,groovy,indent=0,subs="verbatim,quotes"]
[source,java,indent=0,subs="verbatim,quotes"]
----
String name = "Elvis Presley";
String displayName = (name != null ? name : "Unknown");
----
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]
======
@ -38,9 +38,13 @@ Kotlin:: @@ -38,9 +38,13 @@ Kotlin::
----
======
NOTE: 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).
[NOTE]
====
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:
@ -79,7 +83,7 @@ Kotlin:: @@ -79,7 +83,7 @@ Kotlin::
----
======
[NOTE]
[TIP]
=====
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:
@ -89,7 +93,6 @@ 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}")
----
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.
=====

Loading…
Cancel
Save