开发者

Getting Error in the following Groovy Code.. Whats the problem?

HI all, the following code does not getting executed, the code is

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()

This file name is Test.groovy and when i execute like this groovy Test i'm getting an error like this :

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)

Even though i have defined the total() method, it throws an error? Whats the reason for it?


Regarding the line:

assert [200,500,400] == invoices.items*.total()

invoices.items returns a List<List<LineItem>> so invoices.items*.total() fails because the outer List doesn't have a total() method.

If you want to get the total of each LineItem, just remove the outer List by calling flatten()

assert [1000, 1000, 2000] == invoices.items.flatten()*.total()

If you want to get the total value of each invoice, try the following

assert [2000, 2000] == invoices.items*.sum { it.total() }


Assuming you typed cut'n'paste from your code you have a typo...

class LineItem{
    Product product
    int count
    int total**1**(){
            return product.dollar * count
    }
}

Remove the '1' from the method name and retry.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜