I'm writing some Clojure code that depends upon a number of constants.
They will be used within tight inner loops, so it's important that they will be used and optimised as efficiently as possible by the Clojure compiler+JVM combination. I would normally used a "public static final" constant in Java for the same purpose.
What is the best way to declare these?
The static keyword means the value is the same for every instance of the class. The final keyword means once the variable is assigned a value it can never be changed. The combination of static final in Java is how to create a constant value.
public makes it accessible across other classes. static makes it uniform value across all the class instances. final makes it non-modifiable value. So basically it's a "constant" value which is same across all the class instances and which cannot be modified.
final is the java keyword to declare a constant variable.
Static variables are created when the program starts and destroyed when the program stops. Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class. Default values are same as instance variables.
I think def
-ing things in the global namespace is about as close as you can come.
I believe Clojure 1.3 (or maybe 1.4) allows you to put a ^:constant
tag on a def
, signifying to the compiler that this should be a constant and all references should be resolved at compile-time.
Apparently it's Clojure 1.3, and it's ^:const
, not ^:constant
. See How does Clojure ^:const work? for a summary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With