Question
What is the correct way to exclude java.lang.* from a Clojure namespace?
(ns my-namespace
(:require [clojure.core :refer :exclude [* *1 *2 ...]]))
Answer
In Clojure, the default behavior of the namespace is to automatically include the classes found in the java.lang package. However, when you want to create a namespace that avoids conflicting with the default imports from java.lang, here's how to effectively exclude it from your namespace declaration.
(ns your.namespace
(:require [clojure.core :refer :exclude [String Math Thread]]))
Causes
- Automatic imports from java.lang can lead to conflicts or ambiguity when using common names like `String`, `Math`, or `Thread`.
Solutions
- Use `:require` to selectively import only the necessary Clojure core features while excluding unwanted bindings.
- Utilize `:refer :exclude` to prevent importing specific symbols from other namespaces.
Common Mistakes
Mistake: Not specifying the correct symbols to exclude, leading to unintended shadowing of core functions.
Solution: Always refer to the documentation of the libraries you use to know the included functions.
Mistake: Excluding everything from java.lang may lead to loss of essential functionality.
Solution: Carefully assess what you actually need before broadly excluding packages.
Helpers
- Clojure
- namespace exclusions
- java.lang
- Clojure imports
- clean code practices