1

I'm just new at Groovy and I'm following a simple tutorial. I have this code:

class Example {
static void main(String[] args) {
  // Using a simple println statement to print output to the console
  println('Hello World');
}
}

but when I try it in my IDE, I got the error related to println. I think that the Groovy syntax is not recognized. So, is there a way to write groovy code in a .java file?

2
  • 3
    You write Groovy code in a Groovy file; why would you want it in a Java file? Commented Feb 7, 2017 at 15:23
  • 1
    Use a .groovy file instead. You can write Java code in it (not all Java code is valid Groovy code but most of it). Btw note you don't need parentheses and ;, and also you don't need a class and a main method, you can just execute Groovy code as a script (class and main method are created implicitly). Commented Feb 7, 2017 at 15:36

1 Answer 1

4

Simply: don't do that.

The file extension .java tells each and any reader (may that be a human reader or any kind of tooling):

in here, Java code to be found!

Thus: when you put anything into that file that is not Java, you are simply asking for trouble! (I have seen people doing such things, and you won't believe how much pain that caused on other people working on the same project; so on behalf of all the people around you: please bury this idea. Now!)

You could look at this the other way round: Groovy is very close to Java, so if you think you have to "mix" things - see how far you get doing that within some groovy files!

Sign up to request clarification or add additional context in comments.

5 Comments

"Groovy is very close to Java" Only if you use Java syntax! :)
@m0skit0 Sure. But the point is that you can put most java constructs into groovy files, and it will just work. The groovy interpreter can deal with a lot of java idioms; javac on the other hand doesn't support any groovy stuff ;-)
Absolutely. That's adopting Groovy is so easy, because the learning curve is very smooth :)
The problem is that my application is pure Java and I need to reflect some strings containing pure Java code. Is my approach wrong?
I am not sure what your real problem is. The statement println('Hello World'); is not Java. Period. The only think you could make that work is by having A) a static import for java.lang.System.out.println() and B) by changing to " double quotes. The example you gave includes non-java elements, and an IDE that determines file content based on the file extension does not accept that. Long story short: maybe you rephrase your question to explain more carefully what you actually want to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.