def template = { property, fromValue, toValue -> "$property has been updated from $fromValue to $toValue" }
println template('The CPITracker version', '1.0', '1.1')
println template.call('The CPITracker version', '1.0', '1.1')
def messageClosures = [
{ property, fromValue, toValue -> "$property has been updated from $fromValue to $toValue" },
{ property, fromValue, toValue -> "$property has changed from $fromValue to $toValue" },
{ property, fromValue, toValue -> "$property, which was previously $fromValue, is now $toValue" }
]
5.times {
// Choose a random closure...
def template = messageClosures.get(new Random().nextInt(messageClosures.size()))
// ...and call it
println template.call('The CPITracker version', '1.0', '1.1')
}
The CPITracker version, which was previously 1.0, is now 1.1
The CPITracker version has been updated from 1.0 to 1.1
The CPITracker version has changed from 1.0 to 1.1
The CPITracker version has changed from 1.0 to 1.1
The CPITracker version, which was previously 1.0, is now 1.1
Array
class in the Ruby programming language has a method that does exactly that: sample
. Groovy, sadly, doesn’t. We can fix that, though, with Groovy’s dynamic programming model.ArrayList.metaClass.sample = { delegate.get(new Random().nextInt(delegate.size())) }
delegate
reference refers to the specific ArrayList
instance that receives the call to the new sample
method.// Add the sample method to the ArrayList class dynamically
ArrayList.metaClass.sample = { delegate.get(new Random().nextInt(delegate.size())) }
def messageClosures = [
{ property, fromValue, toValue -> "$property has been updated from $fromValue to $toValue" },
{ property, fromValue, toValue -> "$property has changed from $fromValue to $toValue" },
{ property, fromValue, toValue -> "$property, which was previously $fromValue, is now $toValue" }
]
5.times { println messageClosures.sample().call('The CPITracker version', '1.0', '1.1') }
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
8 | |
5 | |
5 | |
4 | |
4 | |
4 | |
4 | |
4 | |
3 | |
3 |