Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy *. Operators

Tags:

groovy

I'am reading 'Groovy in Action' recently. In chapter 7, it introduced the *. operator . When i run the code about this operator, i get some mistakes.

class Invoice {                                          
    List    items                                        
    Date    date                                         
}                                                        
class LineItem {                                         
    Product product                                      
    int     count                                        
    int total() {                                        
        return product.dollar * count                    
    }                                                    
}                                                        
class Product {                                          
    String  name                                         
    def     dollar                                       
}                                                        

def ulcDate = new Date(107,0,1)
def ulc = new Product(dollar:1499, name:'ULC')           
def ve  = new Product(dollar:499,  name:'Visual Editor') 

def invoices = [                                         
    new Invoice(date:ulcDate, items: [                   
        new LineItem(count:5, product:ulc),              
        new LineItem(count:1, product:ve)                
    ]),                                                  
    new Invoice(date:[107,1,2], items: [                 
        new LineItem(count:4, product:ve)                
    ])                                                   
]                                                        

//error
assert [5*1499, 499, 4*499] == invoices.items*.total()  

The last line will throw a exception. At first, i can explain why this error happend. The invocies is a List, and the element's type is Invoice. So directly using items will make a error. I attempt to fix it by using invoices.collect{it.items*.total()}

But still get a fail assert. So, how can i make the assert success and why invoices*.items*.total() will throw a exception.

like image 461
linuxlsx Avatar asked May 23 '12 07:05

linuxlsx


1 Answers

The result of invoices*. operator is a list, so the result of invoices*.items is a list of lists. flatten() can be applied to a lists and returns a flat list, so you can use it to make a list of LineItems from your list of list of ListItems. You can then apply total() to its elements using the spread operator:

assert [5*1499, 499, 4*499] == invoices*.items.flatten()*.total()
like image 200
Antoine Avatar answered Sep 23 '22 21:09

Antoine