aceminer
aceminer

Reputation: 4295

String array in java to clojure

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?

Upvotes: 1

Views: 1138

Answers (1)

mikera
mikera

Reputation: 106351

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

Upvotes: 5

Related Questions