Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.


Code Block
class A{
  int x,y
  A(x,y){ this.x=x; this.y=y } //2-arg constructor
  String toString(){ "x: $x; y: $y" }
A a
a= [1,2] //2-element list causes 2-arg constructor of A to be called
assert  a.class == A && a.toString() == 'x: 1; y: 2'

Statically-Typed Arrays

We can statically type an Object array variable:


Code Block
//a scalar value is cascadingly wrapped by arrays...
Object[][] ia
ia= 7.5
assert ia in Object[][] && ia.size() == 1 &&
       ia[0] in Object[] && ia[0].size() == 1 &&
       ia[0][0] == 7.5

//a one-dimensional vector value is array-wrapped at the innermost level...
ia= ['a', 'b', 'c']
assert ia in Object[][] && ia.size() == 3 &&
       ia[0] in Object[] && ia[0].size() == 1 &&
       ia[0][0] == 'a' && ia[1][0] == 'b' && ia[2][0] == 'c'


Groovy enables a construct known as an interface, which classes can implement. We can test for implemented interfaces with the 'in' operator:


Code Block
interface X{
  int status= 1 //constant field on interface
  int changeCounter()
class A implements X{
  int counter= 1 //updateable field on class itself
  int changeCounter(){ counter++ }
  int changeStatus(){ status++ }
def a= new A()
a.changeCounter() //field 'counter' can be changed...
try{ a.changeStatus(); assert 0 }catch(e){ assert e in IllegalAccessException }
        //...but field 'status' can't

Static Typing with Interfaces

We can use an interface, instead of a class, to statically type a variable, field, parameter, etc: