The document shows examples of using switch statements in Groovy with different data types and cases. It demonstrates matching strings, regular expressions, ranges, collections, objects, null values, and using a closure as a case.
Injustice - Developers Among Us (SciFiDevCon 2024)
JavaSE7 Launch Event: Java7xGroovy
1.
2.
3. $ time groovy -e 'println "Hello, world!";'
Hello, world!
real 0m1.177s
user 0m1.321s
sys 0m0.171s
$ time groovyclient -e 'println "Hello,
world!";'
Hello, world!
real 0m0.029s
user 0m0.001s
sys 0m0.002s
4.
5.
6.
7. String s = ...
switch (s) {
case "quux":
processQuux(s);
// fall-through
case "foo":
case "bar":
processFooOrBar(s);
break;
case "baz":
processBaz(s);
// fall-through
default:
processDefault(s);
break;
}
8. import java.util.regex.Matcher
Object x = ...
switch (x) {
case "abc": // x "abc"
break
case ~/a(.*)c/: // x
assert Matcher.lastMatcher[0][0] == "abbc"
assert Matcher.lastMatcher[0][1] == "bb"
break
case 1..3: // x 1 3
break
case [1,3,5]: // x 1,3,5
break
// ....
}
9. switch (x) {
// ....
case String: // x String
break
case {it % 2 == 0}: // x
break
case null: // x null
break
case a: // a
// a.isCase(x) true
break
}
10.
11. double highestScore = students
.filter(#{ s -> s.gradYear == 2010 })
.map( #{ s -> s.score })
.max();
12. def highestScore = students.
findAll({ s -> s.gradYear == 2010 }).
collect({ s -> s.score }).
max()
13.
14. InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(“src”);
out = new FileOutputStream(“dst”);
byte[] buf = new byte[8192];
int n = 0;
while((n = in.read(buf)) >= 0) { out.write(buf, 0, n); }
} catch (IOException e) {
//
} finally {
if (in != null) {
try { in.close(); } catch (IOException e) { }
}
if (out != null) {
try { out.close(); } catch (IOException e) { }
}
}
15. try (InputStream in = new FileInputStream(“src”);
OutputStream out = new FileOutputStream(“dst”)) {
byte[] buf = new byte[8192];
int n = 0;
while((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
}
16. new File(“dest”).withOutputStream { out ->
new File(“src”).withInputStream { ins ->
byte[] buf = new byte[8192]
int n = 0
while((n = ins.read(buf)) >= 0) {
out.write(buf, 0, n);
}
}
}
new File("dest") << new File("src").bytes
17.
18. Map<String, Map<String, List<Employee>>> map
= new HashMap<String, Map<String, List<Employee>>>();
Map<String, Map<String, List<Employee>>> map = new HashMap<>();