I got confused with this two lines of coding :
this.class.methods.name
This is called Gpath (Am I right?). Now consider this code :
count = 0
def a = [1,2,3,4,5,5,51,2]
a.findAll { it == 5 }.each { count ++ }
println count
The line:
a.findAll { it == 5 }.each { count ++ }
is called as a method chaining or Gpath?
Literally, I got struck with these two meanings. It will be nice if some one explains the difference between these two.
Thanks in advance.
I’m not sure if I understand the question correctly.
As I see it, in both examples you are using method chaining, simply because you are calling a method in the object that is returned by another method. But, as Arturo mentions, some people confuse method chaining and fluent interfaces. A fluent interface is indeed quite handy if you want to chain methods.
In Groovy, however, you may, instead of coding a fluent interface yourself, use the
withmethod in any object. For example, using the samePersonandAddressclasses that Arturo defined, you can do:Now, GPath, as I understand, is just a way of accessing the properties of an object. For example, if you have the class:
The GPath mechanism in Groovy lets you do things like:
Instead of accessing the bar property with its getter, like
foo.getBar(). Nothing too fancy. But other classes in Groovy also have some GPath magic and there is where things get more interesting. For example, lists let you access properties in their elements the same way you’d access normal properties:As you can see, accessing the bar property on a list of objects that have that property will result in a list with the values of that property for each object in the list. But if you access a property that the elements of the list don’t have, e.g.
foos.baz, it will throw a MissingPropertyException.This is exactly what is happening in:
I, however, consider this behavior to be a little too magic for my taste (unless you are parsing XML, in which case is totally fine). Notice that if the collection returned by the
methodsmethod would be some weird collection that had anameproperty,methods.namewould result in that name instead of the names of each method in the collection. In these cases I prefer to use the (IMO) more explicit version:Wich will give you the same result, but it’s just syntax sugar for:
… and let’s the intention of the expression to be more clear (i.e. “I want the names of each method in
methods“).Finally, and this is quite off-topic, the code:
can be rewritten as:
🙂