It is quite common in dynamic languages for code such as the above example not to throw any error. How can this be?In Java, this would typically fail at compile time. However, in Groovy, it will not fail at compile time, and if codedcorrectly, will also not fail at runtime. In fact, to make this work at runtime, one possibility is to rely onruntime metaprogramming. So just adding this line after the declaration of the Person class is enough:
In the type checking section, we have seen that Groovy provides optional type checking thanks to the@TypeChecked annotation. The type checker runs at compile time and performs a static analysis of dynamic code. Theprogram will behave exactly the same whether type checking has been enabled or not. This means that the @TypeCheckedannotation is neutral in regard to the semantics of a program. Even though it may be necessary to add type informationin the sources so that the program is considered type safe, in the end, the semantics of the program are the same.
While this may sound fine, there is actually one issue with this: type checking of dynamic code, done at compile time, isby definition only correct if no runtime specific behavior occurs. For example, the following program passes type checking:
The performance improvements depend on the kind of program you are executing. If it is I/O bound, the difference betweenstatically compiled code and dynamic code is barely noticeable. On highly CPU intensive code, since the bytecode whichis generated is very close, if not equal, to the one that Java would produce for an equivalent program, the performanceis greatly improved.
The DSL relies on a support class called org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport .This class itself extends org.codehaus.groovy.transform.stc.TypeCheckingExtension .Those two classes define a number of helper methods that will make workingwith the AST easier, especially regarding type checking. One interestingthing to know is that you have access to the type checker. This meansthat you can programmatically call methods of the type checker,including those that allow you to throw compilation errors. 2b1af7f3a8