Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added the 8th point: String concatenation

...

Code Block
java
java
String.metaClass.class = Integer  // results in 'abc'.getClass()==java.lang.Integer

8. String concatenation
As in Java, you can concatenate Strings with the "" symbol. But Java only needs that one of the two items of a "" expression to be a String, no matter if it's in the first place or in the last one. Java will use the toString() method in the non-String object of your "" expression. But in Groovy, you just should be safe the first item of your "" expression implements the plus() method in the right way, because Groovy will search and use it. In Groovy GDK, only the Number and String/StringBuffer/Character classes have the plugs() method implemented to concatenate strings. To avoid surprises, always use GStrings.

Code Block
java
java

// Java code, it works
boolean v = true;
System.out.println(" foo "+v);
System.out.println(v+" foo ");
Code Block
java
java

// Groovy code
boolean v = true
println " foo "+v   // It works
println v+" foo "   // It fails with MissingMethodException: No signature of method: java.lang.Boolean.plus()