1

すべてのコレクションにメソッドを追加してproduct()、使用できるように使用したいと思いますsum()。行くことですでにリストの製品を手に入れることがx.inject { a, b -> a * b }できますが、行きたいと思っています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)
4

2 に答える 2

1

Groovy Console でコードを実行してテストできるソリューションを次に示します。

// implement method
Collection.metaClass.product = {

  if (!delegate) {
    return null
  }

  delegate.inject {a, b ->  a * b}
}

// test it
assert [1,2,3].product() == 6
assert [].product() == null

少し長くなりますが、より読みやすい (IMO) ソリューションは次のとおりです。

Collection.metaClass.product = {

  if (!delegate) {
    return null
  }

  def result = 1

  delegate.each {
    result *= it
  }
  result
}
于 2013-01-30T09:16:25.850 に答える
1

理解した。

まったく奇妙な理由が何であれ、groovysh は を許可しましx.inject { a, b -> a * b }たが、実際に groovysh の外でコンパイルすると、これが爆発しました。に変更するとx.inject(1) { a, b -> a * b }、すべてが期待どおりに機能します。

于 2013-01-30T23:41:10.397 に答える