Courses/CS 537/Summer 2008/Control structures

From CSWiki

Jump to: navigation, search

Groovy's control structures are mainly like Java's. An interesting extension is the switch statement. Instead of the control logic testing to see if the item being matched matches a case, the case elements are called (with their isCase() method to see if they return true.

class SwitchExample {
 def testValue
 
 SwitchExample(test) {testValue = test}
 
 boolean isCase(obj) {return obj < testValue}
}
 
def switchExample = new SwitchExample(5)
 
def x = 3
 
switch (x) {
 
  // Calls switchExample.isCase(x)
  case switchExample : println "$x < $switchExample.testValue"; break; // => 3 < 5
 
  default : println "$x > $switchExample.testValue"
}
 
switchExample = new SwitchExample(2)
 
x = 6
 
switch (x) {
 
  // Calls switchExample.isCase(x)
  case switchExample : println "$x < $switchExample.testValue"; break;
 
  default : println "$x > $switchExample.testValue" // => 6 > 2
}

Most Groovy objects have isCase() methods.

switch (10) {
  case 0           : assert false; break
  case 0 .. 9      : assert false; break
  case [8, 9, 11]  : assert false; break
  case Float       : assert false; break // Type
  case {it%3 == 0} : assert false; break // Closure
  case ~/../       : assert true;  break // Regular expression. 
                                         // "10" has 2 characters.
                                         // This case matches.
  default          : assert false; break
}

[edit] private and final

Groovy doesn't seem to support private or final.

class Final {
  final private int x = 9;
}
 
def f = new Final(x:10)
assert 10 == f.x++
assert 11 == f.x

The mailing says that this is a known issue and that there is still some debate about whether it should be allowed. Since Java allows one to get past final and private with reflection, perhaps Groovy should provide something similar but more direct.

Personal tools