In the Java/C world, people often use enums. If I'm using a Java library which using enums, I can convert between them and keywords, for example, using (. java.lang.Enum valueOf e..., (aget ^"[Ljava.lang.Enum;" (. e (getEnumConstants)) i)
, and some reflection. But in the Clojure world, do people ever need anything like an enum (a named integer) ? If not, how is their code structured that they don't need them ? If yes, what's the equivalent ? I sense I'm really asking about indices (for looping), which are rarely used in functional programming (I've used map-indexed only once so far).
The problem with enums is described in Fowler's Refactoring, where it is considered a code smell. It has nothing to do with type safety, but rather that it forces you to sprinkle switch statements all over your code, thus violating the DRY Principle.
The advantage of an enum is that they are a strongly typed value. There are no advantages to using strings.
Comparisons of enums usually are faster than comparisons of strings.
Enumeration is created by using a keyword called “enum”. Given below is the syntax with which we can create an enumeration. Note: enum can be defined only inside a top-level class or interface or in a static context. It should not be inside a method.
For almost all the Clojure code I have seen keywords tend to be used instead of Enums they are name-spaced and have all the other useful properties of keywords while being much easier to write. They are not an exact standin because they are more dynamic (as in dynamic typing) than Java enums
as for indexing and looping I find it more idiomatic to map over a sequence of keywords:
(map do-stuff [:a :b :c :d] (range))
than to loop over the values in an enumeration, which I have yet to find an example of in Clojure code, though an example very likely exists ;-)
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