Improve documentation for SpEL Elvis operator
This commit is contained in:
parent
f8a82b46c1
commit
d3d951e44b
|
@ -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::
|
|||
----
|
||||
======
|
||||
|
||||
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::
|
|||
----
|
||||
======
|
||||
|
||||
[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:
|
|||
@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…
Reference in New Issue