全部,以下代码未执行,代码为
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(name:'ULC', dollar:200)
def ve = new Product(name:'Visual Editor',dollar:500)
def invoices =[new Invoice(date:ulcDate, items: [new LineItem(count:5, product:ulc),new LineItem(count:2, product:ve)]), new Invoice(date:[107,1,1],items:[new LineItem(count:4,product:ve)])]
assert [200,500,400] == invoices.items*.total()
此文件名为Test.groovy
,当我执行此groovy Test
时,我收到如下错误:
Caught: groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.total() is applicable for argument types: () values: []
Possible solutions: tail(), getAt(groovy.lang.Range), getAt(java.util.Collection), getAt(int), getAt(java.lang.String), getAt(java.lang.String)
at In1.run(In1.groovy:20)
即使我定义了total()
方法,它也会抛出错误?是什么原因?
答案 0 :(得分:4)
关于这一行:
assert [200,500,400] == invoices.items*.total()
invoices.items
返回List<List<LineItem>>
,因此invoices.items*.total()
失败,因为外部List
没有total()
方法。
如果您想获得每个LineItem的总数,只需通过调用List
删除外部flatten()
assert [1000, 1000, 2000] == invoices.items.flatten()*.total()
如果您想获得每张发票的总价值,请尝试以下
assert [2000, 2000] == invoices.items*.sum { it.total() }
答案 1 :(得分:0)
假设你从你的代码中输入了cut'n'paste,那你就错了......
class LineItem{
Product product
int count
int total**1**(){
return product.dollar * count
}
}
从方法名称中删除“1”并重试。