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, '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)

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值