Groovy错误笔记1
今天抽了一点时间学习了一下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,0)">? ? 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) ?} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |