您的位置:首页 > 其它

Groovy错误笔记1

2016-07-07 17:55 302 查看
今天抽了一点时间学习了一下Groovy的类定义,感觉基本上跟java差不多,于是跟着pdf照抄了一段,谁知道报错了:

class Money {

    private int amount

    private String currency    

    Money (amountValue, currencyValue) {

        amount = amountValue

        currency = currencyValue

    }    

    boolean equals (Object other) {

        if (null == other) return false

        if (!(other instanceof Money)) return false

        if (currency != other.currency) return false

        if (amount != other.amount) return false

        return true

    }    

    int hashCode() {

        amount.hashCode() + currency.hashCode()

    }    

    Money plus (Money other) {

        if (null == other) return null

        if (other.currency != currency) {

            throw new IllegalArgumentException(

                "cannot add $other.currency to $currency")

            return new Money(amount + other.amount, currency)

        }

    }

}

def buck = new Money(1, 'USD')

assert buck

assert buck == new Money(1 ,'USD')

assert buck + buck == new Money(2, 'USD')

我们在类中重写了plus、hashCode、equals方法,运行以后报:

Exception thrown

Assertion failed:

assert buck + buck == new Money(2, 'USD')

       |    | |    |  |

       |    | |    |  Money@14968

       |    | |    false

       |    | Money@14967

       |    null

       Money@14967sert buck + buck == new Money(2, 'USD')

 

 

java.lang.IllegalArgumentException: bad position: 976

at javax.swing.text.JTextComponent.moveCaretPosition(JTextComponent.java:1551)

at javax.swing.text.JTextComponent$moveCaretPosition$5.call(Unknown Source)

at groovy.ui.Console.hyperlinkUpdate(Console.groovy:1333)

at javax.swing.JEditorPane.fireHyperlinkUpdate(JEditorPane.java:345)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

那就找错吧,测试发现plus方法写错了,没有返回值了,唉,将蓝色的那句话放到外面就行了,正确的写法

Money plus (Money other) {

        if (null == other) return null

        if (other.currency != currency) {

            throw new IllegalArgumentException(

                "cannot add $other.currency to $currency")          

        }

 return new Money(amount + other.amount, currency)

 }

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  groovy