Is there any equivalent in Groovy to Ruby's Object#tap method that passes the object to a closure where the object becomes self and then returns the object? I know about DefaultGroovyMethods.with but that requires you to explicitly return the object in order to be able to chain it or assign it. If not, is there any way that I can implement it myself and have it be available for all objects like the other methods in DefaultGroovyMethods? It's easy enough to take the implementation of DefaultGroovyMethods.with and always return the object instead of the return value of the closure, but can it be made available to all objects? According to this post there's no way to extend DefaultGroovyMethods but is there any other way to do it?
There's no similar method that I know of in groovy, but you should be able to do:
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With