Load Third-Party .Jar Files in the Kotlin REPL

Brian Grogan Jr.
Qualitas Ex Machina
2 min readJul 7, 2020
Photo by Milan Popovic on Unsplash

The REPL (read-eval-print-loop) is a feature that seems to get overlooked far too often. REPL sessions offer a quick and convenient way to try out snippets of code, and with the right start-up option, you can easily load classpaths and .jar files to explore third-party libraries too.

To get ready to explore, install the stand-alone Apache Ivy utility. On macOS, I used the Homebrew package manager to install ivy:

$ brew install ivy

With the stand-alone Apache Ivy utility installed, you can download individual third-party libraries, along with their transitive dependencies, on the fly, outside of a project, with no pom.xml file required. The library’s .jar files will download to the default cache directory.

For an example, we’ll try downloading the OkHttp library from the wonderful developers at Square:

$ ivy -dependency com.squareup.okhttp3 okhttp 4.7.2 -cachepath classes 

This ivy command downloads OkHttp from Maven Central, specified with the dependency option by giving the Group ID, Artifact ID, and Version. The cachepath option generates a file containing a very useful listing of all the .jar paths related to this dependency.

With the OkHttp library downloaded, start up the Kotlin REPL with the classpath option and a reference to the classes cachepath file:

$ kotlin -cp $(< classes)
>>>

Using the cp (classpath) option makes the Kotlin REPL expand the classpath it uses to resolve references to classes. The value passed to the classpath option uses input re-direction and command substitution to generate a list of the third-party .jar files needed for OkHttp.

Inside the REPL session, now we can try using the OkHttp library to make a quick HTTP request:

$ kotlin -cp $(< classes)
>>> import okhttp3.Request
>>> import okhttp3.OkHttpClient
>>> val request = Request.Builder().
... url("https://api.github.com/emojis").
... build()
>>> val response = OkHttpClient().newCall(request).execute()
>>> response.code
res1: kotlin.Int = 200

… and the import statements load the necessary classes, and the HTTP request completes successfully! 👌

Using the Kotlin REPL together with the Apache Ivy utility gives you a very quick and convenient way to get started with a third-party library. You can skip all the typical steps of setting up a project, specifying dependencies, and compiling builds, and instead focus on running code and getting results in an interactive and responsive way.

--

--

Brian Grogan Jr.
Qualitas Ex Machina

Software Quality Engineer fighting for truth, justice, and better quality apps. Thinks a lot about Automation and CI/CD, in both practical and abstract terms.