What "require" statement to use Java library from Clojars

702 Views Asked by At

Most Clojure libraries give information not only on what to put in the project.clj file, but also how to require the library within the source file. For example, https://github.com/clojure/data.json provides a Usage section:

(ns example
  (:require [clojure.data.json :as json]))

I want to use a Clojars library (it’s a Java library), which is listed on Clojars: https://clojars.org/zololabs/jericho-html-parser. I have successfully added the dependency to my project.clj file, but I don’t know how to require it.

I have tried (require '[zololabs.jericho-html-parser]) and numerous variants, but none seems to work. I have looked at the naming conventions of libraries I know how to require to see if I could discern the pattern, but I have not succeeded.

Is there a straightforward way to tell, based on the file name, Leiningen coordinates, or other information, how to require the library?

2

There are 2 best solutions below

0
On BEST ANSWER

First off, you don't require a Java library from Clojure, you import one or more Java classes. For example:

(:import [net.htmlparser.jericho Source TextExtractor])

Then you use those classes via Java interop. e.g.

(Source. (java.net.URL. "https://yahoo.com"))

Note that you don't need to import Java classes already in the classpath in order to use them. You can avoid the import and just refer to them by their fully qualified name if you're going to use them once or twice:

(net.htmlparser.jericho.Source. (java.net.URL. "https://www.yahoo.com"))

Obviously you need to look up the Java library API first and understand how it works. In this particular case, see here.

0
On

You have just discovered one of the inconsistancies in Clojure.

The short answer is that you are missing a colon, which is required for the (ns ...) form used in a source file:

(ns example
  (:require [clojure.data.json :as json]))

Note that since ns is a macro, the source file version doesn't require a single-quote before the left-square-brace.

The other case is using the (require ...) function at the REPL. In this case, you need the syntax:

> (require '[clojure.data.json :as json])

where the > is the REPL prompt. In this case, you are calling a function, so there is no colon before the require. However, since the function is not a macro, you do need to quote the vector specifying the library name and its alias.