When/why would I want to use Groovy's @CompileStatic?

To cite my part of my answer to Should I use Groovy's @CompileStatic if I'm also using Java 7:

While faster than normal Groovy, it can compile only a subset of Groovy and behaves a bit different. Especially all the dynamic features are not available anymore.

All of the MOP will be bypassed. Builders won't work in general, some have extensions to the compiler to allow them passing though. Also methods are selected at compile time using static types, while Groovy normally uses the methods available at runtime and the runtime types. This can result in different methods being called.

Of course @CompileStatic also provides some security, since it is the tasks of a compiler to verify programs at runtime. But since static information is doomed to be incomplete, there can never be a 100% security.

So where is it a no-brainer... well... POGOs for example, since they don't usually contain all that much code. And of course for classes ported from Java to Groovy by copy&paste.

Where would I want it? Well, currently probably on Android, since there the code size has an impact and the static compiled code is more compact. Otherwise I personally am fine with not using @CompileStatic at all. This is more a matter of taste. In some cases there is a performance improvement for tight loops, but that requires you going and identifying by profiling your application first


Turns out that @CompileStatic can be useful when AOT compiling groovy programs - for example with GraalVM native-image tool. The native-image MethodHandle support is limited to cases where the MethodHandle object is a compile time constant. By using compiler configuration like:

import groovy.transform.CompileStatic
withConfig(configuration) {
    ast(CompileStatic)
}

one can eliminate the dynamic MethodHandle instances in the generated bytecode and let the GraalVM ahead-of-time compilation succeed.