【问题标题】:Can I partial a Java method invocation in Clojure?我可以在 Clojure 中对 Java 方法调用进行部分处理吗?
【发布时间】:2013-12-29 12:14:14
【问题描述】:

我有一个对象的方法。

myObject.myMethod(1)

我可以在 Clojure 中调用它

(.myMethod myObject 1)

我也可以使用来自词法环境的信息来调用它

(let [x 1] (.myMethod myObject x))

我可以用部分做这个吗?例如

(let [myPartial (partial .myMethod myObject)]
      (myPartial 1))

这给了我一个

java.lang.RuntimeException: Unable to resolve symbol: .myMethod in this context

我目前正在使用匿名函数进行这项工作

(let [myThing #(.myMethod myObject %)]
      (myThing 1))

但如果在这种情况下使用分部会很好。有可能吗?

我确信答案将与绑定和调度有关,但我还不知道在编译和执行期间调度发生在哪里。

【问题讨论】:

    标签: clojure clojure-java-interop


    【解决方案1】:

    在你的情况下,你可以使用部分,使用 (memfn)。

    (memfn myMethod args)
    

    在 REPL 中:

    user=> (doc memfn)
    -------------------------
    clojure.core/memfn
    ([name & args])
    Macro
    Expands into code that creates a fn that expects to be passed an
    object and any args and calls the named instance method on the
    object passing the args. Use when you want to treat a Java method as
    a first-class fn. name may be type-hinted with the method receiver's
    type in order to avoid reflective calls.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      相关资源
      最近更新 更多