You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2021/07/19 14:00:16 UTC

[groovy] branch master updated: GROOVY-9272: Switch expression (additional documentation)

This is an automated email from the ASF dual-hosted git repository.

paulk pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git


The following commit(s) were added to refs/heads/master by this push:
     new e958e31  GROOVY-9272: Switch expression (additional documentation)
e958e31 is described below

commit e958e318c130dea41235ebd1f001f5b3422560d6
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Jul 19 23:59:53 2021 +1000

    GROOVY-9272: Switch expression (additional documentation)
---
 src/spec/doc/core-semantics.adoc   |  7 +++++++
 src/spec/test/SemanticsTest.groovy | 15 ++++++++++++++-
 2 files changed, 21 insertions(+), 1 deletion(-)

diff --git a/src/spec/doc/core-semantics.adoc b/src/spec/doc/core-semantics.adoc
index 4b3e0b3..697c2b6 100644
--- a/src/spec/doc/core-semantics.adoc
+++ b/src/spec/doc/core-semantics.adoc
@@ -189,6 +189,13 @@ Switch supports the following kinds of comparisons:
 
 NOTE: When using a closure case value, the default `it` parameter is actually the switch value (in our example, variable `x`).
 
+Groovy also supports switch expressions as shown in the following example:
+
+[source,groovy]
+----
+include::../test/SemanticsTest.groovy[tags=switch_expression,indent=0]
+----
+
 ==== Looping structures
 ===== Classic for loop
 
diff --git a/src/spec/test/SemanticsTest.groovy b/src/spec/test/SemanticsTest.groovy
index cc0e9a1..e991913 100644
--- a/src/spec/test/SemanticsTest.groovy
+++ b/src/spec/test/SemanticsTest.groovy
@@ -120,7 +120,7 @@ class SemanticsTest extends CompilableTestSupport {
         def x = 1.23
         def result = ""
 
-        switch ( x ) {
+        switch (x) {
             case "foo":
                 result = "found foo"
                 // lets fall through
@@ -160,6 +160,19 @@ class SemanticsTest extends CompilableTestSupport {
         // end::switch_case_example[]
     }
 
+    void testSwitchExpression() {
+        def person = 'Romeo'
+        // tag::switch_expression[]
+        def partner = switch(person) {
+            case 'Romeo'  -> 'Juliet'
+            case 'Adam'   -> 'Eve'
+            case 'Antony' -> 'Cleopatra'
+            case 'Bonnie' -> 'Clyde'
+        }
+        // end::switch_expression[]
+        assert partner == 'Juliet'
+    }
+
     void testClassicForLoop() {
         // tag::classic_for_loop_example[]
         String message = ''