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 06:49:50 UTC

[groovy-website] branch asf-site updated: Add switch expressions to Groovy 4 release notes (tweak null explanation)

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

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


The following commit(s) were added to refs/heads/asf-site by this push:
     new d5806d3  Add switch expressions to Groovy 4 release notes (tweak null explanation)
d5806d3 is described below

commit d5806d30c5fde39c78cd3b8d1a6c9aab395ba5af
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Jul 19 16:49:45 2021 +1000

    Add switch expressions to Groovy 4 release notes (tweak null explanation)
---
 site/src/site/releasenotes/groovy-4.0.adoc | 22 +++++++++++++++++++++-
 1 file changed, 21 insertions(+), 1 deletion(-)

diff --git a/site/src/site/releasenotes/groovy-4.0.adoc b/site/src/site/releasenotes/groovy-4.0.adoc
index d28df4e..685b489 100644
--- a/site/src/site/releasenotes/groovy-4.0.adoc
+++ b/site/src/site/releasenotes/groovy-4.0.adoc
@@ -248,7 +248,27 @@ test()
 ==== Differences to Java
 
 * Currently, there is no requirement that all possible values of the switch target
-are covered exhaustively by case branches.
+are covered exhaustively by case branches. If no `default` branch is present, an
+implicit one returning `null` is added. For this reason, in contexts where `null`
+is not desired, e.g.&nbsp;storing the result in a primitive, or constructing
+a non-nullable `Optional`, then an explicit `default` should be given, e.g.:
+
+[source,groovy]
+--------------------------------------
+// default branch avoids GroovyCastException
+int i = switch(s) {
+    case 'one' -> 1
+    case 'two' -> 2
+    default -> 0
+}
+
+// default branch avoids NullPointerException
+Optional.of(switch(i) {
+    case 1 -> 'one'
+    case 2 -> 'two'
+    default -> 'buckle my shoe'
+})
+--------------------------------------
 
 [[Groovy4.0-new-checkers]]
 === Built-in type checkers