| Type Params | Return Type | Name and description |
|---|---|---|
|
static Object |
tap(Object self, Closure c)Taken from Ruby, the tap method executes the closure
using the object as the delegate – internally, it just calls
self.with c and then it returns the object it was
called on. |
|
static Object |
withClosable(Object self, Closure c)Will execute closure passing 'self' as a parameter to the closure. |
Taken from Ruby, the tap method executes the closure
using the object as the delegate – internally, it just calls
self.with c and then it returns the object it was
called on.
This allows you to tap into a method chain
def m = (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]
// and returns:
assert m == [4, 16, 36, 64, 100]
self - the object to call the delegate closure onc - the closure to runWill execute closure passing 'self' as a parameter to the closure. When the closure has run, self will be flattened (if it is a list) and close will be called on every item in it (if it responds to a zero-arg version of 'close').
// A class that responds to close()
class A {
boolean isClosed = false
def close() {
isClosed = true
}
}
// Make an instance and test
def obj = new A()
def result = obj.withClosable {
'cool'
}
// Check the result
assert result == 'cool'
// Assert obj is closed
assert obj.isClosed
def list = [ new A(), 'tim', new A() ]
result = list.withClosable {
'also cool'
}
// Check the result
assert result == 'also cool'
// Assert all A instances are closed
assert list.grep( A )*.isClosed.every()
self - the object to call 'close' on after the closure has runc - the closure to run