Chapter 7
Protocols and Datatypes

Abstractions lay at the foundation of reusable code. The Clojure language itself has abstractions for sequences, collections, and callability. Traditionally, these abstractions were described with Java interfaces and implemented using Java classes. In the beginning, Clojure provided proxy and gen-class, removing the need to drop all the way to Java to achieve this, but that changed with the introduction of protocols.

  • Protocols provide an alternative to Java interfaces for high-performance polymorphic method dispatch.

  • Datatypes provide an alternative to Java classes for creating implementations of abstractions defined with either protocols or interfaces.

Protocols and datatypes provide a high-performance, flexible mechanism for abstraction and concretion that removes the need to write Java interfaces and classes when programming in Clojure. With protocols and datatypes, you can create new abstractions and new types that implement those abstractions and even extend new abstractions to existing types.

In this chapter, we’ll explore Clojure’s approach to abstraction using protocols and datatypes. First, we will implement our own version of Clojure’s built-in spit and slurp functions. Then, we’ll take a short detour to build a CryptoVault, where you’ll learn about extending some of Java’s standard library. Finally, we’ll put everything together using records and protocols to define musical notes and sequences. After working through these exercises, you will certainly see the power of Clojure’s composable abstractions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.108.175