Groovy Spread Operator

The spread operator (*) is used to tear a list apart into single elements. This can be used to invoke a method with multiple parameters and then spread a list into the values for the parameters. The spread operator can also be used to add lists or ranges to lists and to add maps to other maps.


class Simple {
    String speak(Integer nString textDate date{
        def out new StringBuffer()
        n.times {
            out << "Say $text on ${date.format('yyyy-MM-dd')}.\n"
        }
        out
    }
}
 
// Spread params list for speak() method.
def params [
    2,
    "hello world",
    new Date().parse("yyyy/MM/dd""2009/09/01")
]
assert '''Say hello world on 2009-09-01.
Say hello world on 2009-09-01.
''' == new Simple().speak(*params)
 
// Add a list to another list.
def list ['Groovy''Java']
assert ['Groovy''Java''Scala'== [*list'Scala']
 
// Add a range to a list.
def range 2..5
assert [123456== [1*range6]
 
// Add a map to another map.
def map [name'mrhaki'blogtrue]
assert [name'mrhaki'blogtruesubject'Groovy Goodness'== [subject'Groovy Goodness'*:map]
 
// Little trick to simulate named parameters for a method.
// It is just a trick so the ordering of the map key/values
// must be the same as the method parameters.
def paramsMap [
    n1,
    text'hello',
    datenew Date().parse("yyyy/MM/dd""2009/09/04")
]
def paramsList paramsMap.values().toList()
assert 'Say hello on 2009-09-04.\n' == new Simple().speak(*paramsList)

Comments

Popular posts from this blog

தட்டு வண்டியில் காளிக்கோயில் - சிறுகதை

பிரேமாவின் பெண் குழந்தை

தீபம் பிளக்ஸ்