Is Groovy syntax an exact superset of Java syntax?

前端 未结 4 1830
春和景丽
春和景丽 2021-01-01 10:06

Being a Java programmer, I don\'t really have a Groovy background, but I use Groovy a lot lately to extend Maven (using GMaven). So far, I could use all the Java code I need

相关标签:
4条回答
  • 2021-01-01 10:10

    There's a page on the Groovy site which documents some of the differences, and another page which lists gotchas (such as the newline thing)

    There are other things as well, one example being that Groovy doesn't support the do...while looping construct

    0 讨论(0)
  • 2021-01-01 10:13

    It isn't.

    My favorite incompatibility: literal arrays:

    String[] s = new String[] {"a", "b", "c"};
    

    In Groovy, curly braces in this context would be expected to contain a closure, not a literal array.

    0 讨论(0)
  • 2021-01-01 10:19

    Others have already given examples of Java syntax that is illegal in Groovy (e.g. literal arrays). It is also worth remembering that some syntax which is legal in both, does not mean the same thing in both languages. For example in Java:

    foo == bar
    

    tests for identity, i.e. do foo and bar both refer to the same object? In Groovy, this tests for object equality, i.e. it returns the result of foo.equals(bar)

    0 讨论(0)
  • 2021-01-01 10:30

    Nope. The following are keywords in groovy, but not Java:

    any    as     def    in     with
    

    Additionally, while not keywords, delegate and owner have special meaning in closures and can trip you up if you're not careful.

    Additionally, there are some minor differences in the language syntax. For one thing, Java is more flexible about where array braces occur in declarations:

    public static void main(String args[]) // valid java, error in groovy
    

    Groovy is parsed differently, too. Here's an example:

    public class Test {
        public static void main(String[] args) {
            int i = 0;
            i = 5
            +1;
            System.out.println(i);
        }
    }
    

    Java will print 6, groovy will print 5.

    While groovy is mostly source compatible with java, there are lots of corner cases that aren't the same. That said, it is very compatible with the code people actually write.

    0 讨论(0)
提交回复
热议问题