1

If i would have a String array in java

Example

public static void main (String [] args)
{
      int x = Integer.parseInt(args[2]);
}

What would be the equivalent of this code in clojure?

1 Answer 1

5

Clojure can call Java methods directly, so assuming your function is passed a String array you can just do:

(defn my-parse [args]
  (Integer/parseInt (aget args 2)))

Things to note:

  • aget is a function that gets an element from a Java array.
  • The syntax (ClassName/methodName ...) is used to call a Java static method in Clojure
  • Clojure will use reflection automatically when needed to select the right method implementation. So in this case, it doesn't need to know at compile time what type of object is stored in the args array - it will work out at runtime that they are Strings and treat them accordingly

It's also worth noting that Clojure can actually destructure Java arrays. So you could also do:

(defn my-parse [[s0 s1 s2 & more-strings]]
  (Integer/parseInt s2))

In this code, s0 takes the value of the first array element, s1 the second, s2 the third and more-strings is a sequence of any remaining arguments

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

3 Comments

Since this object would be called in a loop in java, i would extract an element in the array for everytime the loop is called and update it into another array in java. What would the equivalent of this code in clojure.
@aceminer - not quite sure what you mean - probably should be a separate question?
Perhaps i could start another question which might be clearer for you.

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.