Groovy *.操作符
发布时间:2020-12-14 16:30:52 所属栏目:大数据 来源:网络整理
导读:我最近在阅读“Groovy in Action”.在第7章中,它介绍了*.操作符.当我运行有关此运算符的代码时,我会遇到一些错误. class Invoice { List items Date date } class LineItem { Product product int count int total() { return product.dollar * count } } cl
我最近在阅读“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,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() 最后一行将抛出异常. 但仍然会失败断言.那么,我怎样才能使断言成功以及为什么发票* .items * .total()会抛出异常. 解决方法
发票*的结果. operator是一个列表,因此发票* .items的结果是一个列表列表. flatten()可以应用于列表并返回一个平面列表,因此您可以使用它从ListItem列表列表中创建LineItem列表.然后,您可以使用spread运算符将total()应用于其元素:
assert [5*1499,4*499] == invoices*.items.flatten()*.total() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |