Groovy equivalent of Ruby Object # tap

Is there an equivalent in Groovy to the Ruby Object # tap method that passes the object in closure, where the object becomes itself, and then returns the object? I know about DefaultGroovyMethods.sith, but it requires that you explicitly return the object in order to be able to bind it or assign it. If not, is there a way that I can implement it myself and have it for all objects, such as other methods in DefaultGroovyMethods? It is easy enough to implement the implementation of DefaultGroovyMethods.with and always return an object instead of the return value of the closure, but can it be available for all objects? According to this post , there is no way to extend the DefaultGroovyMethods methods, but is there any other way to do this?

+7
groovy
source share
1 answer

There is no similar method that I know in groovy, but you should be able to:

Object.metaClass.tap = { Closure c -> delegate.with c delegate } (1..10) .tap { println "original ${it}" } .findAll { it % 2 == 0 } .tap { println "evens ${it}" } .collect { it * it } .tap { println "squares ${it}" } 

prints:

 original [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens [2, 4, 6, 8, 10] squares [4, 16, 36, 64, 100] 
+13
source share

All Articles