Static Type Checking
Static type checking (STC) provides information about whether your script is correctly written.
Groovy is a dynamic language, which means that method and property names are looked up when your code is run, not when it's compiled (like Java).
Let's look at the following simple, but complete, script:
foo.bar()We call the method bar() on the object foo. This script compiles without errors, but you get a MissingPropertyException when you run the script because foo hasn't been defined. This behaviour is useful because there are circumstances that could make this code execute successfully, like an object called foo or a closure getFoo() being passed to the script's binding.
Although Groovy is a dynamic language, we can compile scripts in a manner that checks method and property references at compilation. The STC feature shows you problems in your scripts when you are writing them, as opposed to when they execute.
When your scripts are executed, they are always compiled dynamically. When they are compiled for the STC, the resulting generated bytecode is thrown away.
Limitations
There are limitations to the type checker. It is possible to write code that shows errors in the editor, but is valid and executes fine. Some of these situations are:
- Using certain builders: Builder patterns may confuse type inference.
- Using closures where the parameter types can't be inferred: See the Closures section for workarounds.
- Using Spock test framework blocks: When writing Spock tests (extending
spock.lang.Specification), the static type checker cannot infer types correctly within Spock's DSL blocks (expect:,when:,then:,setup:, etc.). Expressions in these blocks are treated as operating onjava.lang.Object, resulting in false-positive errors. These errors can be safely ignored, and the tests will compile and run correctly when executed via the Test Runner or your IDE.
If you write code that triggers these limitations, you may prefer to use an IDE, which does not rely on the STC.
Additionally, your code may contain runtime errors that won't be detected until it executes.