Groovy adds some nice operators to the language to write brief code. We already learned about the Elvis operator and the Spaceship operator. And now we see what the spread-dot operator is about and what it does.
The spread-dot operator (*.) is used to invoke a method on all members of a Collection object. The result of using the spread-dot operator is another Collection object. Here is some sample code:
class Language {
String lang
def speak() { "$lang speaks." }
}
// Create a list with 3 objects. Each object has a lang
// property and a speak() method.
def list = [
new Language(lang: 'Groovy'),
new Language(lang: 'Java'),
new Language(lang: 'Scala')
]
// Use the spread-dot operator to invoke the speak() method.
assert ['Groovy speaks.', 'Java speaks.', 'Scala speaks.'] == list*.speak()
assert ['Groovy speaks.', 'Java speaks.', 'Scala speaks.'] == list.collect{ it.speak() }
// We can also use the spread-dot operator to access
// properties, but we don't need to, because Groovy allows
// direct property access on list members.
assert ['Groovy', 'Java', 'Scala'] == list*.lang
assert ['Groovy', 'Java', 'Scala'] == list.lang
3 comments:
What a nice birthday present :)
When I try running this using these versions: "Groovy Version: 1.6.4 JVM: 1.5.0_18" I get this error when it tries to do 'list*.say()':
Caught: groovy.lang.MissingMethodException: No signature of method: groovy.util.Expando.say() is applicable for argument types: () values: []
at Groovy_Goodness__The_Spread_Dot_Operator.run(Groovy_Goodness__The_Spread_Dot_Operator.groovy:15)
It doesn't like trying to use the spread-dot operator when all members don't define the say() method?
@Anonymous: thank you for finding the "bug". I changed the sample code to make it work. Indeed all members must have the method, because otherwise you get the exception you already encountered.
Post a Comment