There are many ways how to define extension methods for existing types in Groovy, e.g. meta-class, categories, extension modules etc. I'd like to know, which of them are compatible with static compilation via @CompileStatic. I know that it is possible to put a pre-built extension module jar into the classpath providing an extension method for e.g. String and then write a @CompileStatic Groovy class which uses the extension methods from the extension module. However, I'd like to have a solution where I can define extension methods in the same project so that I don't have to build the extension module in advance. Is this possible in Groovy?
Asked
Active
Viewed 347 times
1
-
1I assume you tried and it didn't work? What did you try? – tim_yates Mar 30 '19 at 15:11
-
https://stackoverflow.com/questions/38697952/building-a-project-with-groovy-extension-methods-in-it – tim_yates Mar 30 '19 at 15:42
-
Do you insinuate that the possibilities I listed should work? Well, I tried to define an extension module in the same project where I want to use it and it works, but not when I add @CompileStatic. To be honest I didn't try categories with "use" and also not the meta-class, but I'm 99% sure they won't work because they're inherently dynamic. Traits is not an option because it's no less verbose than using static methods. EDIT: Thanks for the link, but the answer proposes a separate project, whereas I wanted to know whether there is a single project solution. – Werner Thumann Mar 30 '19 at 15:46
-
I've done some digging about, and I don't think there's a single project solution. Extension methods require the methods to be compiled before they are attached – tim_yates Mar 30 '19 at 16:04
-
Hmm ok, what a pity. Anyway, thanks for investigating. If your confidence is, say, >88%, I could mark a simple "No" answer as accepted. ;-) – Werner Thumann Mar 30 '19 at 16:29
-
1I found [this post from Cédric](https://discuss.gradle.org/t/groovy-extension-modules-do-not-work-with-static-compilation-using-the-gradle-compiler/7593/28) who wrote the static compiler. I don't believe anything has changed...but I may be wrong... I'd put confidence at around 85%, so would feel tight taking points for it I think the issue is that groovy scans the classpath looking for extension definitions on startup. Which therefore have to exist on the classpath at startup, which means they can't be compiled as part of the same step – tim_yates Mar 30 '19 at 17:02
-
1Enough confidence for me, I guess the answer to my question is simply no. Thanks! The extra source set might be the best workaround. – Werner Thumann Mar 30 '19 at 17:11
-
Not sure, never tried it with extension method, but I have precompiled AST transforms, using source sets in Gradle, from the same project... – virtualdogbert Mar 31 '19 at 01:17
1 Answers
0
Answer from tim_yates in the comments: Most probably not possible, see here.

Werner Thumann
- 465
- 4
- 15