Valid Java code that is NOT valid Groovy code?

后端 未结 8 2097
忘了有多久
忘了有多久 2020-12-05 04:50

Most Java code is also syntactically valid Groovy code. However, there are a few exceptions which leads me to my question:

Which constructs/features in Java are syn

8条回答
  •  孤街浪徒
    2020-12-05 05:19

    Complementing the answer by Peter Dolberg:

    Besides valid Java code that is not valid in Groovy, you also need to be wary of code that is valid in both Java and Groovy, but has different results in Groovy. Obvious examples are char literals and GStrings:

    System.out.println(String.valueOf('3' + 3)); // 54 in Java, 33 in Groovy (arithmetic ascii value vs. String concat)
    
    System.out.println("${3+4}");
    

    Implicit accessors:

    class Foo {public static int counter; public static int bar; public static void getBar() {counter++; return bar;}}
    System.out.println(Foo.bar);
    System.out.println(Foo.counter); // 0 in Java, 1 in Groovy
    

    toString() has been overwritten by GroovyDefaultMethods, which can bite you when you parse the result.

    Map someMap = new HashMap();
    someMap.put("a", "b")
    someMap.toString();
    

    The equals operation

    "foo" == "foo"
    class Foo {public boolean equals() {return true;}}
    new Foo() == new Foo()
    

    Some operator precedence:

    a *= b/100; // Groovy: (a *= b)/100; Java: a *= (b/100);
    

    This is not a correct answer to the original question, since the groovy code is still syntactically valid in itself, but since it has a different result, I think it is worthwhile mentioning it here. The result is that algorithmically, a method may return the wrong(invalid) result when copied from Java to Groovy.

提交回复
热议问题