如何在 Clojure 中使用 java 方法作为函数参数?
比如我想做一个函数组合:
user> (Integer. (str \9))
9
user> ((comp Integer. str) \9)
CompilerException java.lang.ClassNotFoundException: Integer., compiling:(NO_SOURCE_PATH:1:2)
那行不通。
memfn
也没有帮助:
user> (map (comp (memfn Integer.) str) "891")
IllegalArgumentException No matching method found: Integer. for class java.lang.String clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:53)
有什么想法吗?
相关问题(虽然没有给出问题的正确答案):
- Using interop constructor in map function(Clojure)
- Why does Clojure say "no matching method" for an illegal argument?
- How do I use Clojure memfn with a Java constructor?
- How to get an Fn which calls a Java method? (在答案中有很好的解释)
(注意:dave 建议的答案,使用匿名函数作为包装器,似乎是最好的解决方案)
最佳答案
与 Clojure 函数不同,Java 方法并非设计为一流的。当您在 Clojure 中使用 Java 互操作时,实际上是在使用 Java 方法,因此您不会获得为 Clojure 函数实现的额外好处。有关详细信息,请参阅下面的评论。
作为将 Java 方法用作参数的解决方法,您可以将它们包装在一个匿名函数中,就像这样,有效地使它们成为 Clojure 函数:
((comp #(Integer. %) str) \9)
关于java - 在 Clojure 中使用 java 方法作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23118435/