Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of java methods as a function argument in Clojure

Tags:

java

clojure

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) 

That does not work.

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)

Any ideas?

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)

(Note: it seems to be that the answer suggested by dave, using of an anonymous function as a wrapper, is the best solution)

like image 574
Igor Chubin Avatar asked Oct 27 '25 13:10

Igor Chubin


1 Answers

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.

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)
like image 176
Dave Yarwood Avatar answered Oct 30 '25 14:10

Dave Yarwood