Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy equivalent of Ruby's Object#tap

Tags:

groovy

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?

like image 298
Will Gorman Avatar asked Jul 31 '13 03:07

Will Gorman


Video Answer


1 Answers

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]
like image 51
tim_yates Avatar answered Sep 25 '22 16:09

tim_yates