Groovy’s spread and elvis operators are very elegant and from my experience I see that they are under used. Lets checkout the following code to see what spread and elvis operators can do for us.

1) Spread Operator used when we want to do an operation on a collection of objects

class Author {
    String name
    Book[] books
}
 
class Book {
    String name
}
 
def authors = []
def authorA = new Author(name:"GroovyGuy" ,books: [new Book(name:"groovy"), new Book(name:"grails")])
def authorB = new Author(name:"RubyGuy" ,books: [new Book(name:"ruby"), new Book(name:"rails")])
 
authors << authorA << authorB
 
//I want book names by authorA
println authorA*.books*.name
--> ["groovy", "grails"]
 
//I want all books names by all authors
println authors*.books*.name.flatten()
--> ["groovy", "grails", "ruby", "rails"]
 
println authors*.name
--> ["GroovyGuy", "RubyGuy"]
 
//we can also get list of books by doing this. but if we have a null object in either authors or books
//we get an null pointer exception. so spread takes cares
//of safe navigation on collection
println authors.books.name.flatten()
--> ["groovy", "grails", "ruby", "rails"]

2) Elvis oprator can be used to assign a default value to an object if it happens to be null or empty

def rockstar
def defaultrockstar = rockstar?:"Elvis Presley"
println defaultrockstar
-->"Elvis Presley"

2 Comments

  1. Kenrick Chien says:

    I really like the spread-dot operator as well, but it can be a source of confusion for some. I’m not sure if it’s what you intended, but in Groovy 1.6.2 (and probably earlier versions as well), the first example of yours will actually produce a List containing a List.

    It’s only necessary to use the spread-dot operator following the books property, since you are working on one Author instance.

    Also, for the second example, you can also leave off the spread-dot operator before the books property, because Groovy will treat a property on a list the same way as if you specified spread-dot.

  2. Steve says:

    Yes, you are correct. Actually, you don’t even need the spread-dot operator following the books property on the first example — GPath will kick in and help out! :)

Leave a Reply