简体   繁体   中英

How do you get Clojure to use multiple libraries? What's the Clojure equivalent to folder.* in Java?

I'm curious how to get multiple files to import as part of a larger folder system?

Say I'm using leiningen and I provide the:dependencies keyword in my project.clj file with the right argument for leiningen to find my library. I understand that I can simply provide my source file with "(:use [folder.file])" and it'll know to reference that specific file when I call functions from it, but how do I get it to do that for ALL files in that folder? What's the Clojure way of doing this thing you can do in Java with "file.*"?

Clojure does not have wildcard requires of namespaces (nor wildcard imports of Java classes). It just really isn't necessary in Clojure because namespaces tend to be fairly large, flat collections of related functions -- because we don't have classes like Java, we don't tend to have thousands of files.

At work, we have a pretty large Clojure codebase: 113k lines. It's broken down like this:

Clojure source 361 files 89724 total loc,
    3557 fns, 939 of which are private,
    570 vars, 30 macros, 90 atoms,
    85 agents, 24 protocols, 67 records,
    858 specs, 33 function specs.
Clojure tests 379 files 23795 total loc,
    4 specs, 1 function specs.

So the average source namespace is ~250 lines and has ~10 functions in it. We have a few namespaces that are over 1,000 lines (and one that's over 2,000 lines). A few namespaces require in a "lot" of other namespaces but that's pretty rare: I'd say most of our namespaces only bring in about half a dozen namespaces.

There's also no hierarchy in Clojure namespaces. It's common for a project to adopt a unique prefix for its namespaces, such as next.jdbc for the most popular JDBC library, and even when it has "sub-namespaces", such as next.jdbc.connection that's just another grouping -- there's no semantic of nesting or grouping.

Clojure's explicit "require" brings some benefits. The intent is clear, the effects are less vulnerable to future additions to the directory, you can more easily refactor without tools, and if you use tools you get more on-topic live-typing suggestions.

But "require" is certainly not the only way to introduce symbols to a namespace; Namespaces are open. you may suit yourself: For example: Zach Tellman's "potemkin" library ( https://github.com/clj-commons/potemkin ) can fuse symbols from multiple namespaces into one that can be require'd.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM