Groovy *. operators

I read 'Groovy in action' recently. In chapter 7 she introduced *. the operator. When I run the code about this statement, I get some errors.

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 throws an exception. At first I can explain why this error occurred. Invoke is a List, and the item type is Invoice. Therefore, the direct use of elements will result in an error. I am trying to fix this using invoices.collect{it.items*.total()}

But still get a fail statement. So, how can I make an affirmative success and why will invoices * .items * .total () throw an exception.

+6
source share
2 answers

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

 assert [5*1499, 499, 4*499] == invoices*.items.flatten()*.total() 
+7
source

This does not answer your question, but it is best to also have a general method in your account class:

 int total() { items*.total().sum() } 

Then you can check this with:

 assert [5*1499 + 499, 4*499] == invoices*.total() 
+5
source

Source: https://habr.com/ru/post/916425/


All Articles