Search code examples
clojurecomments

What is the difference between #_ and ; in Clojure?


I know that we use ; for commenting in Clojure, which is equivalent of // in Java. But I cannot understand why we need #_

Can someone please explain this? Is it used to ignore text? How is it different from ; if that is the case?


Solution

  • ; is a line comment; it ignores the text from ; to the end of the line in your source. This also means, that sometimes a comment on the last line leads to lines with just closing parens, which usually is avoided. The main usecase for ; is to write comments for humans to read.

    #_ is called discard; it ignores the next form, which means it is agnostic of line breaks in your source file. This is primarily used to quickly "toggle" code. You can also stack #_. E.g. {#_#_ :a 42}.

    Note, that there is also the (comment ...) macro, which throws away the body and returns nil; so the body must be "valid" and you are well advised not use it, where the result could cause havoc. This is primarily used to provide some "prove of concept" inside the source or code you can quickly run in the REPL, but should not run as part of the ns, or when you are to lazy to write a proper test.