在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
help also:
memfn
doesn't help also:
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):
- 在地图函数中使用interop构造函数(Clojure )
- 为什么Clojure说没有匹配的方法
- 如何使用Java构造函数使用Clojure 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 inter-op时,你实际上正在使用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屋!