Hi,
Is there a detailed explanation for results obtained on evaluating the following on REPL.
(.PI Math)
gives
IllegalArgument Exception
while
(. Math PI)
evaluates to
3.141592653589793
Hi,
Is there a detailed explanation for results obtained on evaluating the following on REPL.
(.PI Math)
gives
IllegalArgument Exception
while
(. Math PI)
evaluates to
3.141592653589793
The explanation is at http://clojure.org/java_interop.
user> (macroexpand '(.PI Math))
(. (clojure.core/identity Math) PI)
(identity Math)
returns the Class
object representing the Math
class. You're trying to access an instance member called PI
in this Class
object, but it doesn't exist. (This is different from accessing a static member called PI
in the Math
class.) You would only ever use this Class
object for reflection, or to pass a Class around to other methods as an Object, or those sorts of things.
user> (class (identity Math))
java.lang.Class
user> (.getName (identity Math))
"java.lang.Math"
user> (.getName Math)
"java.lang.Math"
user> (.getMethods Math)
#<Method[] [Ljava.lang.reflect.Method;@12344e8>
user> (vec (.getMethods Math))
[#<Method public static int java.lang.Math.abs(int)> #<Method public static long java.lang.Math.abs(long)> #<Method public static float java.lang.Math.abs(float)> ...]
user> (.getField Math "PI")
#<Field public static final double java.lang.Math.PI>
user> (.getDouble (.getField Math "PI") Math)
3.141592653589793
The shortest way to do what you want is probably Math/PI
.
user> (macroexpand '(Math/PI))
(. Math PI)
user> Math/PI
3.141592653589793
user> (. Math PI)
3.141592653589793