【发布时间】:2015-07-20 16:42:20
【问题描述】:
在 Groovy 中,我可以重载运算符 '+' plus,如下所示:
class MutableInt {
int val
MutableInt(int val) { this.val = val }
MutableInt plus(int val) {
return new MutableInt(this.val += val)
}
}
上述类适用于以下测试用例:
def m1 = new MutableInt(1);
assert (m1 + 1).val == 2;
但是,如果我需要像这样将它与Map 一起使用并使用静态编译它
@groovy.transform.CompileStatic
void compileItWithStatic() {
Map<Long, MutableInt> mutMap = [:].withDefault{ new MutableInt(0) }
assert (mutMap[1L] += 20).val == 20;
}
compileItWithStatic()
我收到以下错误:
*Script1.groovy: 17: [Static type checking] -
Cannot call <K,V> java.util.Map <java.lang.Long, MutableInt>#putAt(java.lang.Long, MutableInt) with arguments [long, int]*
如何覆盖“+=”运算符并使用静态编译它而不会出错?
编辑:
如果我在没有编译静态的情况下这样做,它可以正常工作:
def m1 = new MutableInt(1);
assert (m1 += 1).val == 2 // <----- caution: '+=' not '+' as in previous case
但是,如果它在这样的方法内部:
@groovy.transform.CompileStatic
void compileItWithStatic_2() {
def m1 = new MutableInt(1);
assert (m1 += 1).val == 2
}
错误将是:
Script1.groovy: -1: Access to java.lang.Object#val is forbidden @ line -1, column -1.
1 error
附注它不适用于静态编译而不是动态编译。
【问题讨论】:
标签: groovy compiler-errors operator-overloading