Wikipedia's current article about the Groovy programming language explains that "Most valid Java files are also valid Groovy files" and gives the following examples, first of Java code:
for (String it : new String[] {"Rod", "Carlos", "Chris"})
if (it.length() <= 4)
System.out.println(it);
Then the same in Groovy:
["Rod", "Carlos", "Chris"].findAll{it.size() <= 4}.each{println it}
Notice in the first example that we used the perfectly ordinary Java method, java.lang.String.length(). In the second example this method has been mysteriously replaced with a call to a method called size()
. I have verified that the second example is valid Groovy code and has the correct behaviour.
java.lang.String
does not have a method called size()
. Groovy does not subclass String
for its own purposes:
String s = ""
Class c = s.getClass()
println c.getName() // "java.lang.String"
nor does it somehow add extra methods to the String
object:
// [...]
for (def method : c.getMethods()) {
println method.getName()
}
// prints a whole bunch of method names, no "size"
and yet still this code somehow works:
// [...]
println s.size() // "0"
I can't find any Groovy documentation to explain this.
- Where does
size()
come from? - Why does it not appear on the object?
- Why was it added?
- What was wrong with
length()
and why is it not preferred? - What other extra methods have been added to
java.lang.String
? - What about other standard classes?
length()
was not really consistent (much lessArray.length
!) while the collections API usessize()
. – Alanizsize
method, andlength
is still there – Entropylength()
had been replaced, because it doesn't make sense to have two methods which do exactly the same thing. – Chiaki