Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

We can restrict the types of values a variable may hold by specifying some restricting class instead of 'def':

When we assign values not of a variable's type to the variable, sometimes it may be 'cast' to the type, other times an exception is thrown:

We can statically type Closure parameters. The casting is more restrictive than for assigning to variables:

We can also statically type the variable-numbered parameters in a closure:

We can statically type function parameters:

We can statically type the return type from a function. Casting a returned value of a different type follows the same rules as for assigning to variables:

We can statically type method parameters just like we do with function parameters, including selecting a method based on its parameter types, for both static methods and instance methods:

We can statically type the return type from a method, just as we can from a function, both static and instance methods:

Property getters and setters can accept and return any statically-typed value:

A list can be cast to a class using that class's constructor:

Statically-Typed Arrays

We can statically type an Object array variable:

We can statically type a variable not only as an array, but as a certain type of array:

We can instead statically type each array element:

Statically typing both the variable and each element allows both array assignments and element assignments to be cast or disallowed:

A multidimensional array type casts its assigned value in various ways:

Interfaces

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

Interfaces can contain method declarations. Each declared method must be defined in implementing classes:

An interface can also be composed of other interfaces, using the 'extends' keyword:

We can implement an interface with map syntax:

Interfaces can also have fields, but their values can't be changed:

Static Typing with Interfaces

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

Groovy supplies many interfaces we can use to statically type variables. Some have no methods, eg, Serializable, while others have one or more:

We've met the Comparator interface in the tutorial on Collections, and the Iterator interface in the tutorial on Control Structures.

Many Groovy classes we've met implement interfaces, which we can use to statically type variables:

  • No labels