在 Clojure 中使用 java 方法作为函数参数 [英] Usage of java methods as a function argument in Clojure
问题描述
如何在 Clojure 中使用 java 方法作为函数参数?
How can I use java methods as a functions arguments in Clojure?
比如我想做一个函数组合:
For example, I want to make a functions composition:
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)
有什么想法吗?
相关问题(尽管没有给出正确答案):
Related questions (that, though, do not give the right answer to the question):
- 在地图函数(Clojure)中使用互操作构造函数
- 为什么 Clojure说没有匹配方法"为非法论点?
- 我如何使用 Clojure带有 Java 构造函数的 memfn?
- 如何获取调用 Java 的 Fn方法?(答案中有很好的解释)
- 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? (has a nice explanation in the answers)
(注意:dave 建议的答案似乎是使用匿名函数作为包装器的最佳解决方案)
推荐答案
与 Clojure 函数不同,Java 方法并非设计为一流的.当您在 Clojure 中使用 Java 互操作时,您实际上是在使用 Java 方法,因此您不会获得为 Clojure 函数实现的额外好处.有关更多信息,请参阅下面的评论.
Unlike Clojure functions, Java methods weren't designed to be first class. When you use Java inter-op in Clojure, you're literally working with Java methods, so you don't get the added benefits that were implemented for Clojure functions. For more info, see the comments below.
作为使用 Java 方法作为参数的一种解决方法,您可以将它们包装在一个匿名函数中,像这样,有效地使它们成为 Clojure 函数:
As a workaround to use Java methods as arguments, you can wrap them in an anonymous function, like this, effectively making them Clojure functions:
((comp #(Integer. %) str) 9)
这篇关于在 Clojure 中使用 java 方法作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!