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:

groovy
foo.bar()

We call the method bar() on the object foo. This script compiles without errors, but you get a MissingPropertyExceptionwhen 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, but it is valid and executes fine. Some of these situations are:

  • Using certain builders

  • Using closures where the parameter types can’t be inferred

However, if you write code like this, you probably use an IDE, which does not work with the STC.

Additionally, your code could have runtime errors that won’t be found until the code executes.

On this page