Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Clojure for Java Developers

You're reading from  Clojure for Java Developers

Product type Book
Published in Feb 2016
Publisher
ISBN-13 9781785281501
Pages 156 pages
Edition 1st Edition
Languages

Protocols in Clojure


Multimethods are just one of the options for polymorphism you have in Clojure, there are other ways to implement polymorphic functions.

Protocols are a little easier to understand and they might feel more similar to Java interfaces.

Lets try to define our shape program using protocols:

(defprotocol Shape
  "This is a protocol for shapes"
  (perimeter [this] "Calculates the perimeter of this shape")
  (area [this] "Calculates the area of this shape"))

Here, we have defined a protocol and it is called shaped and everything that implements this protocol must implement the following two functions: perimeter and area.

There are a number of ways to implement a protocol; one interesting feature is that you can even extend Java classes to implement a protocol without an access to the Java source and without having to recompile anything.

Let's start by creating a record that implements the type.

Records in Clojure

Records work exactly like maps, but they are much faster if you stick...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}