8

I'm very new in learning Clojure. This intended to be my first and very simple Clojure tries in which I call a simple Clojure method from inside java code. Unfortunately it does not work. The Compilation is successful and from the Clojure REPL the written function does as it was ordered, but when calling from Java it says the following:

Exception in thread "main" java.lang.IllegalArgumentException: Wrong number of args (2) passed to: ClojNum$-myinc
 at clojure.lang.AFn.throwArity(AFn.java:439)
 at clojure.lang.AFn.invoke(AFn.java:43)
 at com.experimental.clojure.test.ClojNum.myinc(Unknown Source)
 at com.experimental.clojure.java.JavaCaller.main(JavaCaller.java:14)

Here is the very simple Clojure code:

(ns com.experimental.clojure.test.ClojNum
  (:gen-class
   :init init
   :name com.experimental.clojure.test.ClojNum
   :methods [
             [myinc [int] int]
  ]))

(defn -init [] [[] (atom [])])    
(defn myinc "comment" [x] (+ x 1))    
(defn -myinc "comment" [x] (myinc x))

And the java part:

package com.experimental.clojure.java;

import com.experimental.clojure.test.ClojNum;

public class JavaCaller {
 /**
  * @param args
  */
 public static void main(String[] args) {
  int i = 0;
  System.out.println(i);
  ClojNum c = new ClojNum();
  i = c.myinc(0);  
  System.out.println(i);
 }
}

What did I do wrong? (Note again: This is primitve test code just to make a first successful function call)

Thanks for the help, I'm clueless.

1

1 Answer 1

10

Jeremy's link in the comments show you one way to call a static method in a clojure class. If you want to call a clojure function on an object instance, you need to add a parameter to your wrapper method definition:

(defn -myinc "comment" [this x] (myinc x))

The 'this' parameter is required for any non-static wrapper function. Clojure threw an exception because it received two parameters for a function only defined with one. Note, you do not change anything in your :gen-class :methods section or the myinc function definition itself.

The documentation is a bit sparse, but examples of this can be found at: http://clojure.org/compilation (the last example on the page shows instance methods).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.