我想product()
为所有集合添加一个方法并像我可以使用的那样使用它sum()
。我已经可以通过 go 获得列表的产品x.inject { a, b -> a * b }
,但我希望能够 go x.product()
。
到目前为止我已经尝试过
Collection.metaClass.product = {-> delegate.inject { a, b -> a * b } }
x = [1,2,3,4]
println(x.product())
但这导致
Caught: groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.inject() is applicable for argument types: (Util$_run_closure1_closure2) values: [Util$_run_closure1_closure2@161bb7fe]
Possible solutions: inject(java.lang.Object, groovy.lang.Closure), inject(java.lang.Object, groovy.lang.Closure), inspect(), toSet(), collect(), collect()
groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.inject() is applicable for argument types: (Util$_run_closure1_closure2) values: [Util$_run_closure1_closure2@161bb7fe]
Possible solutions: inject(java.lang.Object, groovy.lang.Closure), inject(java.lang.Object, groovy.lang.Closure), inspect(), toSet(), collect(), collect()
at Util$_run_closure1.doCall(Util.groovy:1)
at Util.run(Util.groovy:4)