Groovy*.运营商

lin*_*lsx 6 groovy

我最近在阅读"Groovy in Action".在第7章中,它介绍了*.运营商.当我运行有关此运算符的代码时,我会遇到一些错误.

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()  
Run Code Online (Sandbox Code Playgroud)

最后一行将抛出异常.首先,我可以解释为什么会发生这种错误.invocies是List,元素的类型是Invoice.所以直接使用项目会出错.我试图通过使用来修复它invoices.collect{it.items*.total()}

但仍然会失败断言.那么,我怎样才能使断言成功以及为什么发票*.items*.total()会抛出异常.

Ant*_*ine 7

invoices*.运算符的结果是一个列表,因此结果invoices*.items是一个列表列表.flatten()可以应用于列表并返回一个平面列表,因此您可以使用它来列出LineItems列表中的列表ListItems.然后,您可以total()使用spread运算符应用于 其元素:

assert [5*1499, 499, 4*499] == invoices*.items.flatten()*.total()
Run Code Online (Sandbox Code Playgroud)


tim*_*tes 5

这不能解答您的问题,但最好在您的Invoice类中使用总方法,如下所示:

int total() {
  items*.total().sum()
}                        
Run Code Online (Sandbox Code Playgroud)

然后你可以用以下方法检查:

assert [5*1499 + 499, 4*499] == invoices*.total()  
Run Code Online (Sandbox Code Playgroud)