在Clojure中使用java方法作为函数参数 [英] Usage of java methods as a function argument in Clojure

查看:125
本文介绍了在Clojure中使用java方法作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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):

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆